blob: d53495f9c81eeba2d467f2463ba6c71008506512 [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
liushenxiang42232912021-05-21 20:24:09 +08001271 // Reset key repeating in case a keyboard device was disabled or enabled.
1272 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1273 resetKeyRepeatLocked();
1274 }
1275
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001276 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 synthesizeCancelationEventsForAllConnectionsLocked(options);
1279 return true;
1280}
1281
Vishnu Nairad321cd2020-08-20 16:40:21 -07001282void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001283 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001284 if (mPendingEvent != nullptr) {
1285 // Move the pending event to the front of the queue. This will give the chance
1286 // for the pending event to get dispatched to the newly focused window
1287 mInboundQueue.push_front(mPendingEvent);
1288 mPendingEvent = nullptr;
1289 }
1290
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001291 std::unique_ptr<FocusEntry> focusEntry =
1292 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1293 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001294
1295 // This event should go to the front of the queue, but behind all other focus events
1296 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001297 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001298 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 [](const std::shared_ptr<EventEntry>& event) {
1300 return event->type == EventEntry::Type::FOCUS;
1301 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302
1303 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001305}
1306
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001308 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001309 if (channel == nullptr) {
1310 return; // Window has gone away
1311 }
1312 InputTarget target;
1313 target.inputChannel = channel;
1314 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1315 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001316 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1317 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001318 std::string reason = std::string("reason=").append(entry->reason);
1319 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001320 dispatchEventLocked(currentTime, entry, {target});
1321}
1322
Prabir Pradhan99987712020-11-10 18:43:05 -08001323void InputDispatcher::dispatchPointerCaptureChangedLocked(
1324 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1325 DropReason& dropReason) {
Prabir Pradhanac483a62021-08-06 14:01:18 +00001326 dropReason = DropReason::NOT_DROPPED;
1327
Prabir Pradhan99987712020-11-10 18:43:05 -08001328 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001329 sp<IBinder> token;
Prabir Pradhanac483a62021-08-06 14:01:18 +00001330
1331 if (entry->pointerCaptureRequest.enable) {
1332 // Enable Pointer Capture.
1333 if (haveWindowWithPointerCapture &&
1334 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1335 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1336 "to the window.");
1337 }
1338 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001339 // This can happen if a window requests capture and immediately releases capture.
1340 ALOGW("No window requested Pointer Capture.");
Prabir Pradhanac483a62021-08-06 14:01:18 +00001341 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001342 return;
1343 }
Prabir Pradhanac483a62021-08-06 14:01:18 +00001344 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1345 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1346 return;
1347 }
1348
Vishnu Nairc519ff72021-01-21 08:23:08 -08001349 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001350 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1351 mWindowTokenWithPointerCapture = token;
1352 } else {
Prabir Pradhanac483a62021-08-06 14:01:18 +00001353 // Disable Pointer Capture.
1354 // We do not check if the sequence number matches for requests to disable Pointer Capture
1355 // for two reasons:
1356 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1357 // to disable capture with the same sequence number: one generated by
1358 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1359 // Capture being disabled in InputReader.
1360 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1361 // actual Pointer Capture state that affects events being generated by input devices is
1362 // in InputReader.
1363 if (!haveWindowWithPointerCapture) {
1364 // Pointer capture was already forcefully disabled because of focus change.
1365 dropReason = DropReason::NOT_DROPPED;
1366 return;
1367 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001368 token = mWindowTokenWithPointerCapture;
1369 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanac483a62021-08-06 14:01:18 +00001370 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001371 setPointerCaptureLocked(false);
1372 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001373 }
1374
1375 auto channel = getInputChannelLocked(token);
1376 if (channel == nullptr) {
1377 // Window has gone away, clean up Pointer Capture state.
1378 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanac483a62021-08-06 14:01:18 +00001379 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001380 setPointerCaptureLocked(false);
1381 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001382 return;
1383 }
1384 InputTarget target;
1385 target.inputChannel = channel;
1386 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1387 entry->dispatchInProgress = true;
1388 dispatchEventLocked(currentTime, entry, {target});
1389
1390 dropReason = DropReason::NOT_DROPPED;
1391}
1392
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001393bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001396 if (!entry->dispatchInProgress) {
1397 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1398 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1399 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1400 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001401 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 // We have seen two identical key downs in a row which indicates that the device
1403 // driver is automatically generating key repeats itself. We take note of the
1404 // repeat here, but we disable our own next key repeat timer since it is clear that
1405 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001406 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1407 // Make sure we don't get key down from a different device. If a different
1408 // device Id has same key pressed down, the new device Id will replace the
1409 // current one to hold the key repeat with repeat count reset.
1410 // In the future when got a KEY_UP on the device id, drop it and do not
1411 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1413 resetKeyRepeatLocked();
1414 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1415 } else {
1416 // Not a repeat. Save key down state in case we do see a repeat later.
1417 resetKeyRepeatLocked();
1418 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1419 }
1420 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001421 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1422 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001423 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001424#if DEBUG_INBOUND_EVENT_DETAILS
1425 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1426#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001427 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 resetKeyRepeatLocked();
1429 }
1430
1431 if (entry->repeatCount == 1) {
1432 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1433 } else {
1434 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1435 }
1436
1437 entry->dispatchInProgress = true;
1438
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001439 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 }
1441
1442 // Handle case where the policy asked us to try again later last time.
1443 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1444 if (currentTime < entry->interceptKeyWakeupTime) {
1445 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1446 *nextWakeupTime = entry->interceptKeyWakeupTime;
1447 }
1448 return false; // wait until next wakeup
1449 }
1450 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1451 entry->interceptKeyWakeupTime = 0;
1452 }
1453
1454 // Give the policy a chance to intercept the key.
1455 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1456 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001457 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001458 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001459 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001460 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001461 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001463 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 return false; // wait for the command to run
1465 } else {
1466 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1467 }
1468 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001469 if (*dropReason == DropReason::NOT_DROPPED) {
1470 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 }
1472 }
1473
1474 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001475 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001476 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001477 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1478 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001479 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 return true;
1481 }
1482
1483 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001484 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001485 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001486 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 return false;
1489 }
1490
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001491 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001492 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 return true;
1494 }
1495
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001496 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001497 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498
1499 // Dispatch the key.
1500 dispatchEventLocked(currentTime, entry, inputTargets);
1501 return true;
1502}
1503
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001506 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001507 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1508 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001509 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1510 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1511 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512#endif
1513}
1514
Chris Yef59a2f42020-10-16 12:55:26 -07001515void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1516 mLock.unlock();
1517
1518 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1519 if (entry->accuracyChanged) {
1520 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1521 }
1522 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1523 entry->hwTimestamp, entry->values);
1524 mLock.lock();
1525}
1526
1527void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1528 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1529#if DEBUG_OUTBOUND_EVENT_DETAILS
1530 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1531 "source=0x%x, sensorType=%s",
1532 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001533 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001534#endif
1535 std::unique_ptr<CommandEntry> commandEntry =
1536 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1537 commandEntry->sensorEntry = entry;
1538 postCommandLocked(std::move(commandEntry));
1539}
1540
1541bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1542#if DEBUG_OUTBOUND_EVENT_DETAILS
1543 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1544 NamedEnum::string(sensorType).c_str());
1545#endif
1546 { // acquire lock
1547 std::scoped_lock _l(mLock);
1548
1549 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1550 std::shared_ptr<EventEntry> entry = *it;
1551 if (entry->type == EventEntry::Type::SENSOR) {
1552 it = mInboundQueue.erase(it);
1553 releaseInboundEventLocked(entry);
1554 }
1555 }
1556 }
1557 return true;
1558}
1559
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001560bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001562 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 entry->dispatchInProgress = true;
1566
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
1569
1570 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001571 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001572 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1574 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 return true;
1576 }
1577
1578 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1579
1580 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001581 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582
1583 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001584 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 if (isPointerEvent) {
1586 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001587 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001588 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001589 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 } else {
1591 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001592 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001593 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001595 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 return false;
1597 }
1598
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001599 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001600 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001601 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1602 return true;
1603 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001604 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001605 CancelationOptions::Mode mode(isPointerEvent
1606 ? CancelationOptions::CANCEL_POINTER_EVENTS
1607 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1608 CancelationOptions options(mode, "input event injection failed");
1609 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 return true;
1611 }
1612
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001613 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001614 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001616 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001617 std::unordered_map<int32_t, TouchState>::iterator it =
1618 mTouchStatesByDisplay.find(entry->displayId);
1619 if (it != mTouchStatesByDisplay.end()) {
1620 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001621 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001622 // The event has gone through these portal windows, so we add monitoring targets of
1623 // the corresponding displays as well.
1624 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05001625 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001626 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001628 }
1629 }
1630 }
1631 }
1632
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 // Dispatch the motion.
1634 if (conflictingPointerActions) {
1635 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001636 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 synthesizeCancelationEventsForAllConnectionsLocked(options);
1638 }
1639 dispatchEventLocked(currentTime, entry, inputTargets);
1640 return true;
1641}
1642
chaviw3277faf2021-05-19 16:45:23 -05001643void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001644 bool isExiting, const MotionEntry& motionEntry) {
1645 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1646 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1647 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1648 PointerCoords pointerCoords;
1649 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1650 pointerCoords.transform(windowHandle->getInfo()->transform);
1651
1652 std::unique_ptr<DragEntry> dragEntry =
1653 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1654 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1655 pointerCoords.getY());
1656
1657 enqueueInboundEventLocked(std::move(dragEntry));
1658}
1659
1660void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1661 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1662 if (channel == nullptr) {
1663 return; // Window has gone away
1664 }
1665 InputTarget target;
1666 target.inputChannel = channel;
1667 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1668 entry->dispatchInProgress = true;
1669 dispatchEventLocked(currentTime, entry, {target});
1670}
1671
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001672void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001674 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 ", policyFlags=0x%x, "
1676 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1677 "metaState=0x%x, buttonState=0x%x,"
1678 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001679 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1680 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1681 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001683 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001685 "x=%f, y=%f, pressure=%f, size=%f, "
1686 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1687 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001688 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1689 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1690 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1691 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1692 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1693 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1694 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1695 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1696 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1697 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 }
1699#endif
1700}
1701
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001702void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1703 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001704 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001705 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706#if DEBUG_DISPATCH_CYCLE
1707 ALOGD("dispatchEventToCurrentInputTargets");
1708#endif
1709
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001710 updateInteractionTokensLocked(*eventEntry, inputTargets);
1711
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1713
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001714 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001716 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001717 sp<Connection> connection =
1718 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001719 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001720 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001722 if (DEBUG_FOCUS) {
1723 ALOGD("Dropping event delivery to target with channel '%s' because it "
1724 "is no longer registered with the input dispatcher.",
1725 inputTarget.inputChannel->getName().c_str());
1726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 }
1728 }
1729}
1730
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001731void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1732 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1733 // If the policy decides to close the app, we will get a channel removal event via
1734 // unregisterInputChannel, and will clean up the connection that way. We are already not
1735 // sending new pointers to the connection when it blocked, but focused events will continue to
1736 // pile up.
1737 ALOGW("Canceling events for %s because it is unresponsive",
1738 connection->inputChannel->getName().c_str());
1739 if (connection->status == Connection::STATUS_NORMAL) {
1740 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1741 "application not responding");
1742 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 }
1744}
1745
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001746void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001747 if (DEBUG_FOCUS) {
1748 ALOGD("Resetting ANR timeouts.");
1749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750
1751 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001752 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001753 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754}
1755
Tiger Huang721e26f2018-07-24 22:26:19 +08001756/**
1757 * Get the display id that the given event should go to. If this event specifies a valid display id,
1758 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1759 * Focused display is the display that the user most recently interacted with.
1760 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001761int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001762 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001763 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001764 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001765 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1766 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001767 break;
1768 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001769 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001770 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1771 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001772 break;
1773 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001774 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001775 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001776 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001777 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001778 case EventEntry::Type::SENSOR:
1779 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001780 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001781 return ADISPLAY_ID_NONE;
1782 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001783 }
1784 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1785}
1786
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1788 const char* focusedWindowName) {
1789 if (mAnrTracker.empty()) {
1790 // already processed all events that we waited for
1791 mKeyIsWaitingForEventsTimeout = std::nullopt;
1792 return false;
1793 }
1794
1795 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1796 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001797 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001798 mKeyIsWaitingForEventsTimeout = currentTime +
1799 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1800 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001801 return true;
1802 }
1803
1804 // We still have pending events, and already started the timer
1805 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1806 return true; // Still waiting
1807 }
1808
1809 // Waited too long, and some connection still hasn't processed all motions
1810 // Just send the key to the focused window
1811 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1812 focusedWindowName);
1813 mKeyIsWaitingForEventsTimeout = std::nullopt;
1814 return false;
1815}
1816
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001817InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1818 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1819 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001820 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821
Tiger Huang721e26f2018-07-24 22:26:19 +08001822 int32_t displayId = getTargetDisplayId(entry);
chaviw3277faf2021-05-19 16:45:23 -05001823 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001824 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001825 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1826
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 // If there is no currently focused window and no focused application
1828 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1830 ALOGI("Dropping %s event because there is no focused window or focused application in "
1831 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001832 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001833 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 }
1835
Vishnu Nair41f77b82021-09-03 16:07:44 -07001836 // Drop key events if requested by input feature
1837 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1838 return InputEventInjectionResult::FAILED;
1839 }
1840
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1842 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1843 // start interacting with another application via touch (app switch). This code can be removed
1844 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1845 // an app is expected to have a focused window.
1846 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1847 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1848 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001849 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1850 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1851 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001852 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001853 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854 ALOGW("Waiting because no window has focus but %s may eventually add a "
1855 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001856 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001857 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001859 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1860 // Already raised ANR. Drop the event
1861 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001862 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001864 } else {
1865 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001866 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001867 }
1868 }
1869
1870 // we have a valid, non-null focused window
1871 resetNoFocusedWindowTimeoutLocked();
1872
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001874 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001875 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
1877
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001878 if (focusedWindowHandle->getInfo()->paused) {
1879 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001880 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001881 }
1882
1883 // If the event is a key event, then we must wait for all previous events to
1884 // complete before delivering it because previous events may have the
1885 // side-effect of transferring focus to a different window and we want to
1886 // ensure that the following keys are sent to the new window.
1887 //
1888 // Suppose the user touches a button in a window then immediately presses "A".
1889 // If the button causes a pop-up window to appear then we want to ensure that
1890 // the "A" key is delivered to the new pop-up window. This is because users
1891 // often anticipate pending UI changes when typing on a keyboard.
1892 // To obtain this behavior, we must serialize key events with respect to all
1893 // prior input events.
1894 if (entry.type == EventEntry::Type::KEY) {
1895 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1896 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001897 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 }
1900
1901 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001902 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001903 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1904 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905
1906 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908}
1909
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910/**
1911 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1912 * that are currently unresponsive.
1913 */
1914std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1915 const std::vector<TouchedMonitor>& monitors) const {
1916 std::vector<TouchedMonitor> responsiveMonitors;
1917 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1918 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1919 sp<Connection> connection = getConnectionLocked(
1920 monitor.monitor.inputChannel->getConnectionToken());
1921 if (connection == nullptr) {
1922 ALOGE("Could not find connection for monitor %s",
1923 monitor.monitor.inputChannel->getName().c_str());
1924 return false;
1925 }
1926 if (!connection->responsive) {
1927 ALOGW("Unresponsive monitor %s will not get the new gesture",
1928 connection->inputChannel->getName().c_str());
1929 return false;
1930 }
1931 return true;
1932 });
1933 return responsiveMonitors;
1934}
1935
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001936InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1937 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1938 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001939 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 enum InjectionPermission {
1941 INJECTION_PERMISSION_UNKNOWN,
1942 INJECTION_PERMISSION_GRANTED,
1943 INJECTION_PERMISSION_DENIED
1944 };
1945
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 // For security reasons, we defer updating the touch state until we are sure that
1947 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001948 int32_t displayId = entry.displayId;
1949 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1951
1952 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001953 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw3277faf2021-05-19 16:45:23 -05001955 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1956 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001958 // Copy current touch state into tempTouchState.
1959 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1960 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001961 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001962 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001963 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1964 mTouchStatesByDisplay.find(displayId);
1965 if (oldStateIt != mTouchStatesByDisplay.end()) {
1966 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001967 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001968 }
1969
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001970 bool isSplit = tempTouchState.split;
1971 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1972 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1973 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001974 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1975 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1976 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1977 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1978 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001979 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 bool wrongDevice = false;
1981 if (newGesture) {
1982 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001983 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001984 ALOGI("Dropping event because a pointer for a different device is already down "
1985 "in display %" PRId32,
1986 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001987 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001988 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 switchedDevice = false;
1990 wrongDevice = true;
1991 goto Failed;
1992 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001993 tempTouchState.reset();
1994 tempTouchState.down = down;
1995 tempTouchState.deviceId = entry.deviceId;
1996 tempTouchState.source = entry.source;
1997 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001999 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002000 ALOGI("Dropping move event because a pointer for a different device is already active "
2001 "in display %" PRId32,
2002 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002003 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002004 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002005 switchedDevice = false;
2006 wrongDevice = true;
2007 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009
2010 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2011 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2012
Garfield Tan00f511d2019-06-12 16:55:40 -07002013 int32_t x;
2014 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002016 // Always dispatch mouse events to cursor position.
2017 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 x = int32_t(entry.xCursorPosition);
2019 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002020 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2022 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002023 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002024 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07002025 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002026 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2027 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002028
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002030 if (newTouchedWindowHandle != nullptr &&
2031 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002032 // New window supports splitting, but we should never split mouse events.
2033 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 } else if (isSplit) {
2035 // New window does not support splitting but we have already split events.
2036 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002037 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 }
2039
2040 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002041 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002043 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002044 }
2045
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002046 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2047 ALOGI("Not sending touch event to %s because it is paused",
2048 newTouchedWindowHandle->getName().c_str());
2049 newTouchedWindowHandle = nullptr;
2050 }
2051
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002052 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002053 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002054 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2055 if (!isResponsive) {
2056 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002057 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2058 newTouchedWindowHandle = nullptr;
2059 }
2060 }
2061
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002062 // Drop events that can't be trusted due to occlusion
2063 if (newTouchedWindowHandle != nullptr &&
2064 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2065 TouchOcclusionInfo occlusionInfo =
2066 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002067 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002068 if (DEBUG_TOUCH_OCCLUSION) {
2069 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2070 for (const auto& log : occlusionInfo.debugInfo) {
2071 ALOGD("%s", log.c_str());
2072 }
2073 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002074 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2075 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2076 ALOGW("Dropping untrusted touch event due to %s/%d",
2077 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2078 newTouchedWindowHandle = nullptr;
2079 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002080 }
2081 }
2082
Vishnu Nair41f77b82021-09-03 16:07:44 -07002083 // Drop touch events if requested by input feature
2084 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2085 newTouchedWindowHandle = nullptr;
2086 }
2087
Arthur Hung71625472021-11-16 02:45:54 +00002088 const std::vector<TouchedMonitor> newGestureMonitors = isDown
2089 ? selectResponsiveMonitorsLocked(
2090 findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows))
2091 : tempTouchState.gestureMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092
Michael Wright3dd60e22019-03-27 22:06:44 +00002093 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2094 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 "(%d, %d) in display %" PRId32 ".",
2096 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002097 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002098 goto Failed;
2099 }
2100
2101 if (newTouchedWindowHandle != nullptr) {
2102 // Set target flags.
2103 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2104 if (isSplit) {
2105 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002107 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2108 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2109 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2110 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2111 }
2112
2113 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002114 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2115 newHoverWindowHandle = nullptr;
2116 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002117 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002118 }
2119
2120 // Update the temporary touch state.
2121 BitSet32 pointerIds;
2122 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002124 pointerIds.markBit(pointerId);
2125 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002126 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Arthur Hung71625472021-11-16 02:45:54 +00002127 } else if (tempTouchState.windows.empty()) {
2128 // If no window is touched, set split to true. This will allow the next pointer down to
2129 // be delivered to a new window which supports split touch.
2130 tempTouchState.split = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 }
Arthur Hung71625472021-11-16 02:45:54 +00002132 if (isDown) {
2133 tempTouchState.addGestureMonitors(newGestureMonitors);
2134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 } else {
2136 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2137
2138 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002139 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002140 if (DEBUG_FOCUS) {
2141 ALOGD("Dropping event because the pointer is not down or we previously "
2142 "dropped the pointer down event in display %" PRId32,
2143 displayId);
2144 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002145 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 goto Failed;
2147 }
2148
arthurhung6d4bed92021-03-17 11:59:33 +08002149 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002150
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002152 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002154 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2155 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156
chaviw3277faf2021-05-19 16:45:23 -05002157 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002158 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002159 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair41f77b82021-09-03 16:07:44 -07002160
2161 // Drop touch events if requested by input feature
2162 if (newTouchedWindowHandle != nullptr &&
2163 shouldDropInput(entry, newTouchedWindowHandle)) {
2164 newTouchedWindowHandle = nullptr;
2165 }
2166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002167 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2168 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002169 if (DEBUG_FOCUS) {
2170 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2171 oldTouchedWindowHandle->getName().c_str(),
2172 newTouchedWindowHandle->getName().c_str(), displayId);
2173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002175 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2176 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2177 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178
2179 // Make a slippery entrance into the new window.
2180 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2181 isSplit = true;
2182 }
2183
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002184 int32_t targetFlags =
2185 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 if (isSplit) {
2187 targetFlags |= InputTarget::FLAG_SPLIT;
2188 }
2189 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2190 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002191 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2192 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
2194
2195 BitSet32 pointerIds;
2196 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002197 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002199 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201 }
2202 }
2203
2204 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002205 // Let the previous window know that the hover sequence is over, unless we already did it
2206 // when dispatching it as is to newTouchedWindowHandle.
2207 if (mLastHoverWindowHandle != nullptr &&
2208 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2209 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210#if DEBUG_HOVER
2211 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002212 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002214 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2215 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
2217
Garfield Tandf26e862020-07-01 20:18:19 -07002218 // Let the new window know that the hover sequence is starting, unless we already did it
2219 // when dispatching it as is to newTouchedWindowHandle.
2220 if (newHoverWindowHandle != nullptr &&
2221 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2222 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223#if DEBUG_HOVER
2224 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002225 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2228 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2229 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231 }
2232
2233 // Check permission to inject into all touched foreground windows and ensure there
2234 // is at least one touched foreground window.
2235 {
2236 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002237 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2239 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002240 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002241 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 injectionPermission = INJECTION_PERMISSION_DENIED;
2243 goto Failed;
2244 }
2245 }
2246 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002248 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002249 ALOGI("Dropping event because there is no touched foreground window in display "
2250 "%" PRId32 " or gesture monitor to receive it.",
2251 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002252 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 goto Failed;
2254 }
2255
2256 // Permission granted to injection into all touched foreground windows.
2257 injectionPermission = INJECTION_PERMISSION_GRANTED;
2258 }
2259
2260 // Check whether windows listening for outside touches are owned by the same UID. If it is
2261 // set the policy flag that we will not reveal coordinate information to this window.
2262 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002263 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002264 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002265 if (foregroundWindowHandle) {
2266 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002268 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw3277faf2021-05-19 16:45:23 -05002269 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2270 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2271 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 InputTarget::FLAG_ZERO_COORDS,
2273 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276 }
2277 }
2278 }
2279
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 // If this is the first pointer going down and the touched window has a wallpaper
2281 // then also add the touched wallpaper windows so they are locked in for the duration
2282 // of the touch gesture.
2283 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2284 // engine only supports touch events. We would need to add a mechanism similar
2285 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2286 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002287 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002288 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002289 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw3277faf2021-05-19 16:45:23 -05002290 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002291 getWindowHandlesLocked(displayId);
chaviw3277faf2021-05-19 16:45:23 -05002292 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2293 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002294 if (info->displayId == displayId &&
chaviw3277faf2021-05-19 16:45:23 -05002295 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002296 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 .addOrUpdateWindow(windowHandle,
2298 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2299 InputTarget::
2300 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2301 InputTarget::FLAG_DISPATCH_AS_IS,
2302 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 }
2304 }
2305 }
2306 }
2307
2308 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002309 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002313 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002316 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002317 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002319 }
2320
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 // Drop the outside or hover touch windows since we will not care about them
2322 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002323 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324
2325Failed:
2326 // Check injection permission once and for all.
2327 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 injectionPermission = INJECTION_PERMISSION_GRANTED;
2330 } else {
2331 injectionPermission = INJECTION_PERMISSION_DENIED;
2332 }
2333 }
2334
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002335 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2336 return injectionResult;
2337 }
2338
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002340 if (!wrongDevice) {
2341 if (switchedDevice) {
2342 if (DEBUG_FOCUS) {
2343 ALOGD("Conflicting pointer actions: Switched to a different device.");
2344 }
2345 *outConflictingPointerActions = true;
2346 }
2347
2348 if (isHoverAction) {
2349 // Started hovering, therefore no longer down.
2350 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002351 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002352 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2353 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 *outConflictingPointerActions = true;
2356 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002357 tempTouchState.reset();
2358 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2359 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2360 tempTouchState.deviceId = entry.deviceId;
2361 tempTouchState.source = entry.source;
2362 tempTouchState.displayId = displayId;
2363 }
2364 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2365 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2366 // All pointers up or canceled.
2367 tempTouchState.reset();
2368 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2369 // First pointer went down.
2370 if (oldState && oldState->down) {
2371 if (DEBUG_FOCUS) {
2372 ALOGD("Conflicting pointer actions: Down received while already down.");
2373 }
2374 *outConflictingPointerActions = true;
2375 }
2376 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2377 // One pointer went up.
2378 if (isSplit) {
2379 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2380 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002382 for (size_t i = 0; i < tempTouchState.windows.size();) {
2383 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2384 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2385 touchedWindow.pointerIds.clearBit(pointerId);
2386 if (touchedWindow.pointerIds.isEmpty()) {
2387 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2388 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002391 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002393 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002394 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002395
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002396 // Save changes unless the action was scroll in which case the temporary touch
2397 // state was only valid for this one action.
2398 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2399 if (tempTouchState.displayId >= 0) {
2400 mTouchStatesByDisplay[displayId] = tempTouchState;
2401 } else {
2402 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002406 // Update hover state.
2407 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
2409
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 return injectionResult;
2411}
2412
arthurhung6d4bed92021-03-17 11:59:33 +08002413void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw3277faf2021-05-19 16:45:23 -05002414 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002415 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2416 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2417 true /*ignoreDragWindow*/);
2418 if (dropWindow) {
2419 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2420 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002421 } else {
2422 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002423 }
2424 mDragState.reset();
2425}
2426
2427void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2428 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002429 return;
2430 }
2431
arthurhung6d4bed92021-03-17 11:59:33 +08002432 if (!mDragState->isStartDrag) {
2433 mDragState->isStartDrag = true;
2434 mDragState->isStylusButtonDownAtStart =
2435 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2436 }
2437
arthurhungb89ccb02020-12-30 16:19:01 +08002438 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2439 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2440 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2441 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002442 // Handle the special case : stylus button no longer pressed.
2443 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2444 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2445 finishDragAndDrop(entry.displayId, x, y);
2446 return;
2447 }
2448
chaviw3277faf2021-05-19 16:45:23 -05002449 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002450 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002451 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2452 true /*ignoreDragWindow*/);
2453 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002454 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2455 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2456 if (mDragState->dragHoverWindowHandle != nullptr) {
2457 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2458 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002459 }
arthurhung6d4bed92021-03-17 11:59:33 +08002460 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002461 }
2462 // enqueue drag location if needed.
2463 if (hoverWindowHandle != nullptr) {
2464 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2465 }
arthurhung6d4bed92021-03-17 11:59:33 +08002466 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2467 finishDragAndDrop(entry.displayId, x, y);
2468 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002469 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002470 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002471 }
2472}
2473
chaviw3277faf2021-05-19 16:45:23 -05002474void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 int32_t targetFlags, BitSet32 pointerIds,
2476 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002477 std::vector<InputTarget>::iterator it =
2478 std::find_if(inputTargets.begin(), inputTargets.end(),
2479 [&windowHandle](const InputTarget& inputTarget) {
2480 return inputTarget.inputChannel->getConnectionToken() ==
2481 windowHandle->getToken();
2482 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002483
chaviw3277faf2021-05-19 16:45:23 -05002484 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002485
2486 if (it == inputTargets.end()) {
2487 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002488 std::shared_ptr<InputChannel> inputChannel =
2489 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002490 if (inputChannel == nullptr) {
2491 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2492 return;
2493 }
2494 inputTarget.inputChannel = inputChannel;
2495 inputTarget.flags = targetFlags;
2496 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002497 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002498 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002499 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002500 inputTargets.push_back(inputTarget);
2501 it = inputTargets.end() - 1;
2502 }
2503
2504 ALOG_ASSERT(it->flags == targetFlags);
2505 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2506
chaviw1ff3d1e2020-07-01 15:53:47 -07002507 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508}
2509
Michael Wright3dd60e22019-03-27 22:06:44 +00002510void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 int32_t displayId, float xOffset,
2512 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002513 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2514 mGlobalMonitorsByDisplay.find(displayId);
2515
2516 if (it != mGlobalMonitorsByDisplay.end()) {
2517 const std::vector<Monitor>& monitors = it->second;
2518 for (const Monitor& monitor : monitors) {
2519 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 }
2522}
2523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2525 float yOffset,
2526 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002527 InputTarget target;
2528 target.inputChannel = monitor.inputChannel;
2529 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002530 ui::Transform t;
2531 t.set(xOffset, yOffset);
2532 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002533 inputTargets.push_back(target);
2534}
2535
chaviw3277faf2021-05-19 16:45:23 -05002536bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002537 const InjectionState* injectionState) {
2538 if (injectionState &&
2539 (windowHandle == nullptr ||
2540 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2541 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002542 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 "owned by uid %d",
2545 injectionState->injectorPid, injectionState->injectorUid,
2546 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 } else {
2548 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002549 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 }
2551 return false;
2552 }
2553 return true;
2554}
2555
Robert Carrc9bf1d32020-04-13 17:21:08 -07002556/**
2557 * Indicate whether one window handle should be considered as obscuring
2558 * another window handle. We only check a few preconditions. Actually
2559 * checking the bounds is left to the caller.
2560 */
chaviw3277faf2021-05-19 16:45:23 -05002561static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2562 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002563 // Compare by token so cloned layers aren't counted
2564 if (haveSameToken(windowHandle, otherHandle)) {
2565 return false;
2566 }
2567 auto info = windowHandle->getInfo();
2568 auto otherInfo = otherHandle->getInfo();
2569 if (!otherInfo->visible) {
2570 return false;
chaviw3277faf2021-05-19 16:45:23 -05002571 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002572 // Those act as if they were invisible, so we don't need to flag them.
2573 // We do want to potentially flag touchable windows even if they have 0
2574 // opacity, since they can consume touches and alter the effects of the
2575 // user interaction (eg. apps that rely on
2576 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2577 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2578 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002579 } else if (info->ownerUid == otherInfo->ownerUid) {
2580 // If ownerUid is the same we don't generate occlusion events as there
2581 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002582 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002583 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002584 return false;
2585 } else if (otherInfo->displayId != info->displayId) {
2586 return false;
2587 }
2588 return true;
2589}
2590
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002591/**
2592 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2593 * untrusted, one should check:
2594 *
2595 * 1. If result.hasBlockingOcclusion is true.
2596 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2597 * BLOCK_UNTRUSTED.
2598 *
2599 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2600 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2601 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2602 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2603 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2604 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2605 *
2606 * If neither of those is true, then it means the touch can be allowed.
2607 */
2608InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw3277faf2021-05-19 16:45:23 -05002609 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2610 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002611 int32_t displayId = windowInfo->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002612 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002613 TouchOcclusionInfo info;
2614 info.hasBlockingOcclusion = false;
2615 info.obscuringOpacity = 0;
2616 info.obscuringUid = -1;
2617 std::map<int32_t, float> opacityByUid;
chaviw3277faf2021-05-19 16:45:23 -05002618 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002619 if (windowHandle == otherHandle) {
2620 break; // All future windows are below us. Exit early.
2621 }
chaviw3277faf2021-05-19 16:45:23 -05002622 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002623 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2624 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002625 if (DEBUG_TOUCH_OCCLUSION) {
2626 info.debugInfo.push_back(
2627 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2628 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002629 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2630 // we perform the checks below to see if the touch can be propagated or not based on the
2631 // window's touch occlusion mode
2632 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2633 info.hasBlockingOcclusion = true;
2634 info.obscuringUid = otherInfo->ownerUid;
2635 info.obscuringPackage = otherInfo->packageName;
2636 break;
2637 }
2638 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2639 uint32_t uid = otherInfo->ownerUid;
2640 float opacity =
2641 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2642 // Given windows A and B:
2643 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2644 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2645 opacityByUid[uid] = opacity;
2646 if (opacity > info.obscuringOpacity) {
2647 info.obscuringOpacity = opacity;
2648 info.obscuringUid = uid;
2649 info.obscuringPackage = otherInfo->packageName;
2650 }
2651 }
2652 }
2653 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002654 if (DEBUG_TOUCH_OCCLUSION) {
2655 info.debugInfo.push_back(
2656 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2657 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002658 return info;
2659}
2660
chaviw3277faf2021-05-19 16:45:23 -05002661std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002662 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002663 return StringPrintf(INDENT2
2664 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2665 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2666 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2667 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002668 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002669 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002670 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002671 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2672 info->frameTop, info->frameRight, info->frameBottom,
2673 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002674 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2675 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2676 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002677}
2678
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002679bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2680 if (occlusionInfo.hasBlockingOcclusion) {
2681 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2682 occlusionInfo.obscuringUid);
2683 return false;
2684 }
2685 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2686 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2687 "%.2f, maximum allowed = %.2f)",
2688 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2689 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2690 return false;
2691 }
2692 return true;
2693}
2694
chaviw3277faf2021-05-19 16:45:23 -05002695bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002696 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002698 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2699 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002700 if (windowHandle == otherHandle) {
2701 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 }
chaviw3277faf2021-05-19 16:45:23 -05002703 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002704 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002705 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 return true;
2707 }
2708 }
2709 return false;
2710}
2711
chaviw3277faf2021-05-19 16:45:23 -05002712bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002713 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002714 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2715 const WindowInfo* windowInfo = windowHandle->getInfo();
2716 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002717 if (windowHandle == otherHandle) {
2718 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002719 }
chaviw3277faf2021-05-19 16:45:23 -05002720 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002721 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002722 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002723 return true;
2724 }
2725 }
2726 return false;
2727}
2728
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002729std::string InputDispatcher::getApplicationWindowLabel(
chaviw3277faf2021-05-19 16:45:23 -05002730 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002731 if (applicationHandle != nullptr) {
2732 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002733 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 } else {
2735 return applicationHandle->getName();
2736 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002737 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002738 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002740 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 }
2742}
2743
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002744void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002745 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002746 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2747 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002748 // Focus or pointer capture changed events are passed to apps, but do not represent user
2749 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002750 return;
2751 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002752 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw3277faf2021-05-19 16:45:23 -05002753 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002754 if (focusedWindowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05002755 const WindowInfo* info = focusedWindowHandle->getInfo();
2756 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002758 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759#endif
2760 return;
2761 }
2762 }
2763
2764 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002765 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002766 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002767 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2768 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 return;
2770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002772 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 eventType = USER_ACTIVITY_EVENT_TOUCH;
2774 }
2775 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002777 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002778 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2779 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 return;
2781 }
2782 eventType = USER_ACTIVITY_EVENT_BUTTON;
2783 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002785 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002786 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002787 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002788 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002789 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2790 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002791 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002792 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002793 break;
2794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 }
2796
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002797 std::unique_ptr<CommandEntry> commandEntry =
2798 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002799 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002801 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002802 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803}
2804
2805void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002806 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002807 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002808 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002809 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002810 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002811 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002812 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002813 ATRACE_NAME(message.c_str());
2814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815#if DEBUG_DISPATCH_CYCLE
2816 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002817 "globalScaleFactor=%f, pointerIds=0x%x %s",
2818 connection->getInputChannelName().c_str(), inputTarget.flags,
2819 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2820 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821#endif
2822
2823 // Skip this event if the connection status is not normal.
2824 // We don't want to enqueue additional outbound events if the connection is broken.
2825 if (connection->status != Connection::STATUS_NORMAL) {
2826#if DEBUG_DISPATCH_CYCLE
2827 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829#endif
2830 return;
2831 }
2832
2833 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002834 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2835 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2836 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002837 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002839 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002840 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002841 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002842 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 if (!splitMotionEntry) {
2844 return; // split event was dropped
2845 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002846 if (DEBUG_FOCUS) {
2847 ALOGD("channel '%s' ~ Split motion event.",
2848 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002849 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002850 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002851 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2852 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 return;
2854 }
2855 }
2856
2857 // Not splitting. Enqueue dispatch entries for the event as is.
2858 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2859}
2860
2861void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002862 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002863 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002864 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002865 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002866 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002867 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002868 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002869 ATRACE_NAME(message.c_str());
2870 }
2871
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002872 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873
2874 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002875 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002876 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002877 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002879 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002880 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002881 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002883 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002885 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
2888 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002889 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 startDispatchCycleLocked(currentTime, connection);
2891 }
2892}
2893
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002895 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002896 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002898 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2900 connection->getInputChannelName().c_str(),
2901 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002902 ATRACE_NAME(message.c_str());
2903 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002904 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 if (!(inputTargetFlags & dispatchMode)) {
2906 return;
2907 }
2908 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2909
2910 // This is a new event.
2911 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002912 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002913 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002915 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2916 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002917 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002919 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002920 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002921 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002922 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002923 dispatchEntry->resolvedAction = keyEntry.action;
2924 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2927 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2930 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 return; // skip the inconsistent event
2933 }
2934 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002937 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002938 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002939 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2940 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2941 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2942 static_cast<int32_t>(IdGenerator::Source::OTHER);
2943 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2945 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2946 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2947 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2948 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2949 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2950 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2951 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2952 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2953 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2954 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002955 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002956 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 }
2958 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2960 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2963 "event",
2964 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002966 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2967 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002971 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2973 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2974 }
2975 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2976 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2980 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2983 "event",
2984 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 return; // skip the inconsistent event
2987 }
2988
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002989 dispatchEntry->resolvedEventId =
2990 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2991 ? mIdGenerator.nextId()
2992 : motionEntry.id;
2993 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2994 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2995 ") to MotionEvent(id=0x%" PRIx32 ").",
2996 motionEntry.id, dispatchEntry->resolvedEventId);
2997 ATRACE_NAME(message.c_str());
2998 }
2999
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003000 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3001 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3002 // Skip reporting pointer down outside focus to the policy.
3003 break;
3004 }
3005
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003007 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008
3009 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003011 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003012 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3013 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003014 break;
3015 }
Chris Yef59a2f42020-10-16 12:55:26 -07003016 case EventEntry::Type::SENSOR: {
3017 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3018 break;
3019 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003020 case EventEntry::Type::CONFIGURATION_CHANGED:
3021 case EventEntry::Type::DEVICE_RESET: {
3022 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07003023 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003024 break;
3025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 }
3027
3028 // Remember that we are waiting for this dispatch to complete.
3029 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003030 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 }
3032
3033 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003034 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003035 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003036}
3037
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003038/**
3039 * This function is purely for debugging. It helps us understand where the user interaction
3040 * was taking place. For example, if user is touching launcher, we will see a log that user
3041 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3042 * We will see both launcher and wallpaper in that list.
3043 * Once the interaction with a particular set of connections starts, no new logs will be printed
3044 * until the set of interacted connections changes.
3045 *
3046 * The following items are skipped, to reduce the logspam:
3047 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3048 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3049 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3050 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3051 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003052 */
3053void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3054 const std::vector<InputTarget>& targets) {
3055 // Skip ACTION_UP events, and all events other than keys and motions
3056 if (entry.type == EventEntry::Type::KEY) {
3057 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3058 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3059 return;
3060 }
3061 } else if (entry.type == EventEntry::Type::MOTION) {
3062 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3063 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3064 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3065 return;
3066 }
3067 } else {
3068 return; // Not a key or a motion
3069 }
3070
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003071 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003072 std::vector<sp<Connection>> newConnections;
3073 for (const InputTarget& target : targets) {
3074 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3075 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3076 continue; // Skip windows that receive ACTION_OUTSIDE
3077 }
3078
3079 sp<IBinder> token = target.inputChannel->getConnectionToken();
3080 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003081 if (connection == nullptr) {
3082 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003083 }
3084 newConnectionTokens.insert(std::move(token));
3085 newConnections.emplace_back(connection);
3086 }
3087 if (newConnectionTokens == mInteractionConnectionTokens) {
3088 return; // no change
3089 }
3090 mInteractionConnectionTokens = newConnectionTokens;
3091
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003092 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003093 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003094 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003095 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003096 std::string message = "Interaction with: " + targetList;
3097 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003098 message += "<none>";
3099 }
3100 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3101}
3102
chaviwfd6d3512019-03-25 13:23:49 -07003103void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003104 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003105 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003106 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3107 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003108 return;
3109 }
3110
Vishnu Nairc519ff72021-01-21 08:23:08 -08003111 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003112 if (focusedToken == token) {
3113 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003114 return;
3115 }
3116
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003117 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3118 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003119 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003120 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121}
3122
3123void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003125 if (ATRACE_ENABLED()) {
3126 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003128 ATRACE_NAME(message.c_str());
3129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003131 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132#endif
3133
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003134 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3135 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003137 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003138 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003139 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140
3141 // Publish the event.
3142 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003143 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3144 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003145 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003146 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3147 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003150 status = connection->inputPublisher
3151 .publishKeyEvent(dispatchEntry->seq,
3152 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3153 keyEntry.source, keyEntry.displayId,
3154 std::move(hmac), dispatchEntry->resolvedAction,
3155 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3156 keyEntry.scanCode, keyEntry.metaState,
3157 keyEntry.repeatCount, keyEntry.downTime,
3158 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 }
3161
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003162 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003166 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167
chaviw82357092020-01-28 13:13:06 -08003168 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003169 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3171 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003172 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003173 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3174 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003175 // Don't apply window scale here since we don't want scale to affect raw
3176 // coordinates. The scale will be sent back to the client and applied
3177 // later when requesting relative coordinates.
3178 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3179 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 }
3181 usingCoords = scaledCoords;
3182 }
3183 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 // We don't want the dispatch target to know.
3185 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003186 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 scaledCoords[i].clear();
3188 }
3189 usingCoords = scaledCoords;
3190 }
3191 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003192
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003193 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194
3195 // Publish the motion event.
3196 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003197 .publishMotionEvent(dispatchEntry->seq,
3198 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003199 motionEntry.deviceId, motionEntry.source,
3200 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003201 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003202 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 motionEntry.edgeFlags, motionEntry.metaState,
3205 motionEntry.buttonState,
3206 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003207 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003208 motionEntry.xPrecision, motionEntry.yPrecision,
3209 motionEntry.xCursorPosition,
3210 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003211 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003212 dispatchEntry->displaySize.x,
3213 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003214 motionEntry.downTime, motionEntry.eventTime,
3215 motionEntry.pointerCount,
3216 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 break;
3218 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003219
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003220 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003221 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003222 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 focusEntry.id,
3224 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003225 mInTouchMode);
3226 break;
3227 }
3228
Prabir Pradhan99987712020-11-10 18:43:05 -08003229 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3230 const auto& captureEntry =
3231 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3232 status = connection->inputPublisher
3233 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhanac483a62021-08-06 14:01:18 +00003234 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003235 break;
3236 }
3237
arthurhungb89ccb02020-12-30 16:19:01 +08003238 case EventEntry::Type::DRAG: {
3239 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3240 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3241 dragEntry.id, dragEntry.x,
3242 dragEntry.y,
3243 dragEntry.isExiting);
3244 break;
3245 }
3246
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003247 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003248 case EventEntry::Type::DEVICE_RESET:
3249 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003250 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003251 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 }
3255
3256 // Check the result.
3257 if (status) {
3258 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003259 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 "This is unexpected because the wait queue is empty, so the pipe "
3262 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003263 "event to it, status=%s(%d)",
3264 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3265 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3267 } else {
3268 // Pipe is full and we are waiting for the app to finish process some events
3269 // before sending more events to it.
3270#if DEBUG_DISPATCH_CYCLE
3271 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003272 "waiting for the application to catch up",
3273 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 }
3276 } else {
3277 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003278 "status=%s(%d)",
3279 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3280 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3282 }
3283 return;
3284 }
3285
3286 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003287 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3288 connection->outboundQueue.end(),
3289 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003290 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003291 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003292 if (connection->responsive) {
3293 mAnrTracker.insert(dispatchEntry->timeoutTime,
3294 connection->inputChannel->getConnectionToken());
3295 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003296 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 }
3298}
3299
chaviw09c8d2d2020-08-24 15:48:26 -07003300std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3301 size_t size;
3302 switch (event.type) {
3303 case VerifiedInputEvent::Type::KEY: {
3304 size = sizeof(VerifiedKeyEvent);
3305 break;
3306 }
3307 case VerifiedInputEvent::Type::MOTION: {
3308 size = sizeof(VerifiedMotionEvent);
3309 break;
3310 }
3311 }
3312 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3313 return mHmacKeyManager.sign(start, size);
3314}
3315
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003316const std::array<uint8_t, 32> InputDispatcher::getSignature(
3317 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3318 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3319 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3320 // Only sign events up and down events as the purely move events
3321 // are tied to their up/down counterparts so signing would be redundant.
3322 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3323 verifiedEvent.actionMasked = actionMasked;
3324 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003325 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003326 }
3327 return INVALID_HMAC;
3328}
3329
3330const std::array<uint8_t, 32> InputDispatcher::getSignature(
3331 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3332 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3333 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3334 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003335 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003336}
3337
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003340 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341#if DEBUG_DISPATCH_CYCLE
3342 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344#endif
3345
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 if (connection->status == Connection::STATUS_BROKEN ||
3347 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 return;
3349 }
3350
3351 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003352 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353}
3354
3355void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 const sp<Connection>& connection,
3357 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358#if DEBUG_DISPATCH_CYCLE
3359 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361#endif
3362
3363 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003364 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003365 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003366 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003367 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
3369 // The connection appears to be unrecoverably broken.
3370 // Ignore already broken or zombie connections.
3371 if (connection->status == Connection::STATUS_NORMAL) {
3372 connection->status = Connection::STATUS_BROKEN;
3373
3374 if (notify) {
3375 // Notify other system components.
3376 onDispatchCycleBrokenLocked(currentTime, connection);
3377 }
3378 }
3379}
3380
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003381void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3382 while (!queue.empty()) {
3383 DispatchEntry* dispatchEntry = queue.front();
3384 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003385 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 }
3387}
3388
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003389void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003391 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
3393 delete dispatchEntry;
3394}
3395
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003396int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3397 std::scoped_lock _l(mLock);
3398 sp<Connection> connection = getConnectionLocked(connectionToken);
3399 if (connection == nullptr) {
3400 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3401 connectionToken.get(), events);
3402 return 0; // remove the callback
3403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003405 bool notify;
3406 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3407 if (!(events & ALOOPER_EVENT_INPUT)) {
3408 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3409 "events=0x%x",
3410 connection->getInputChannelName().c_str(), events);
3411 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 }
3413
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003414 nsecs_t currentTime = now();
3415 bool gotOne = false;
3416 status_t status = OK;
3417 for (;;) {
3418 Result<InputPublisher::ConsumerResponse> result =
3419 connection->inputPublisher.receiveConsumerResponse();
3420 if (!result.ok()) {
3421 status = result.error().code();
3422 break;
3423 }
3424
3425 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3426 const InputPublisher::Finished& finish =
3427 std::get<InputPublisher::Finished>(*result);
3428 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3429 finish.consumeTime);
3430 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003431 if (shouldReportMetricsForConnection(*connection)) {
3432 const InputPublisher::Timeline& timeline =
3433 std::get<InputPublisher::Timeline>(*result);
3434 mLatencyTracker
3435 .trackGraphicsLatency(timeline.inputEventId,
3436 connection->inputChannel->getConnectionToken(),
3437 std::move(timeline.graphicsTimeline));
3438 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003439 }
3440 gotOne = true;
3441 }
3442 if (gotOne) {
3443 runCommandsLockedInterruptible();
3444 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 return 1;
3446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 }
3448
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003449 notify = status != DEAD_OBJECT || !connection->monitor;
3450 if (notify) {
3451 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3452 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3453 status);
3454 }
3455 } else {
3456 // Monitor channels are never explicitly unregistered.
3457 // We do it automatically when the remote endpoint is closed so don't warn about them.
3458 const bool stillHaveWindowHandle =
3459 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3460 notify = !connection->monitor && stillHaveWindowHandle;
3461 if (notify) {
3462 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3463 connection->getInputChannelName().c_str(), events);
3464 }
3465 }
3466
3467 // Remove the channel.
3468 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3469 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470}
3471
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003472void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003474 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003475 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 }
3477}
3478
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003479void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003480 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003481 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3482 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3483}
3484
3485void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3486 const CancelationOptions& options,
3487 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3488 for (const auto& it : monitorsByDisplay) {
3489 const std::vector<Monitor>& monitors = it.second;
3490 for (const Monitor& monitor : monitors) {
3491 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003492 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003493 }
3494}
3495
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003497 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003498 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003499 if (connection == nullptr) {
3500 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003502
3503 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504}
3505
3506void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3507 const sp<Connection>& connection, const CancelationOptions& options) {
3508 if (connection->status == Connection::STATUS_BROKEN) {
3509 return;
3510 }
3511
3512 nsecs_t currentTime = now();
3513
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003514 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003515 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003517 if (cancelationEvents.empty()) {
3518 return;
3519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003521 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3522 "with reality: %s, mode=%d.",
3523 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3524 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003526
3527 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003528 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003529 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3530 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003531 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003532 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003533 target.globalScaleFactor = windowInfo->globalScaleFactor;
3534 }
3535 target.inputChannel = connection->inputChannel;
3536 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3537
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003538 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003539 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003540 switch (cancelationEventEntry->type) {
3541 case EventEntry::Type::KEY: {
3542 logOutboundKeyDetails("cancel - ",
3543 static_cast<const KeyEntry&>(*cancelationEventEntry));
3544 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003546 case EventEntry::Type::MOTION: {
3547 logOutboundMotionDetails("cancel - ",
3548 static_cast<const MotionEntry&>(*cancelationEventEntry));
3549 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003551 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003552 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3553 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003554 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003555 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003556 break;
3557 }
3558 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003559 case EventEntry::Type::DEVICE_RESET:
3560 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003561 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003562 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003563 break;
3564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 }
3566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003567 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3568 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003570
3571 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572}
3573
Svet Ganov5d3bc372020-01-26 23:11:07 -08003574void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3575 const sp<Connection>& connection) {
3576 if (connection->status == Connection::STATUS_BROKEN) {
3577 return;
3578 }
3579
3580 nsecs_t currentTime = now();
3581
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003582 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003583 connection->inputState.synthesizePointerDownEvents(currentTime);
3584
3585 if (downEvents.empty()) {
3586 return;
3587 }
3588
3589#if DEBUG_OUTBOUND_EVENT_DETAILS
3590 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3591 connection->getInputChannelName().c_str(), downEvents.size());
3592#endif
3593
3594 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003595 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003596 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3597 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003598 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003599 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003600 target.globalScaleFactor = windowInfo->globalScaleFactor;
3601 }
3602 target.inputChannel = connection->inputChannel;
3603 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3604
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003605 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003606 switch (downEventEntry->type) {
3607 case EventEntry::Type::MOTION: {
3608 logOutboundMotionDetails("down - ",
3609 static_cast<const MotionEntry&>(*downEventEntry));
3610 break;
3611 }
3612
3613 case EventEntry::Type::KEY:
3614 case EventEntry::Type::FOCUS:
3615 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003616 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003617 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003618 case EventEntry::Type::SENSOR:
3619 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003620 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003621 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003622 break;
3623 }
3624 }
3625
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003626 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3627 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003628 }
3629
3630 startDispatchCycleLocked(currentTime, connection);
3631}
3632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003633std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3634 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 ALOG_ASSERT(pointerIds.value != 0);
3636
3637 uint32_t splitPointerIndexMap[MAX_POINTERS];
3638 PointerProperties splitPointerProperties[MAX_POINTERS];
3639 PointerCoords splitPointerCoords[MAX_POINTERS];
3640
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003641 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 uint32_t splitPointerCount = 0;
3643
3644 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003645 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003647 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 uint32_t pointerId = uint32_t(pointerProperties.id);
3649 if (pointerIds.hasBit(pointerId)) {
3650 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3651 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3652 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003653 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 splitPointerCount += 1;
3655 }
3656 }
3657
3658 if (splitPointerCount != pointerIds.count()) {
3659 // This is bad. We are missing some of the pointers that we expected to deliver.
3660 // Most likely this indicates that we received an ACTION_MOVE events that has
3661 // different pointer ids than we expected based on the previous ACTION_DOWN
3662 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3663 // in this way.
3664 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003665 "we expected there to be %d pointers. This probably means we received "
3666 "a broken sequence of pointer ids from the input device.",
3667 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003668 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 }
3670
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003671 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003673 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3674 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3676 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003677 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 uint32_t pointerId = uint32_t(pointerProperties.id);
3679 if (pointerIds.hasBit(pointerId)) {
3680 if (pointerIds.count() == 1) {
3681 // The first/last pointer went down/up.
3682 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003683 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003684 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3685 ? AMOTION_EVENT_ACTION_CANCEL
3686 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 } else {
3688 // A secondary pointer went down/up.
3689 uint32_t splitPointerIndex = 0;
3690 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3691 splitPointerIndex += 1;
3692 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003693 action = maskedAction |
3694 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 }
3696 } else {
3697 // An unrelated pointer changed.
3698 action = AMOTION_EVENT_ACTION_MOVE;
3699 }
3700 }
3701
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003702 int32_t newId = mIdGenerator.nextId();
3703 if (ATRACE_ENABLED()) {
3704 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3705 ") to MotionEvent(id=0x%" PRIx32 ").",
3706 originalMotionEntry.id, newId);
3707 ATRACE_NAME(message.c_str());
3708 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003709 std::unique_ptr<MotionEntry> splitMotionEntry =
3710 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3711 originalMotionEntry.deviceId, originalMotionEntry.source,
3712 originalMotionEntry.displayId,
3713 originalMotionEntry.policyFlags, action,
3714 originalMotionEntry.actionButton,
3715 originalMotionEntry.flags, originalMotionEntry.metaState,
3716 originalMotionEntry.buttonState,
3717 originalMotionEntry.classification,
3718 originalMotionEntry.edgeFlags,
3719 originalMotionEntry.xPrecision,
3720 originalMotionEntry.yPrecision,
3721 originalMotionEntry.xCursorPosition,
3722 originalMotionEntry.yCursorPosition,
3723 originalMotionEntry.downTime, splitPointerCount,
3724 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003726 if (originalMotionEntry.injectionState) {
3727 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 splitMotionEntry->injectionState->refCount += 1;
3729 }
3730
3731 return splitMotionEntry;
3732}
3733
3734void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3735#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003736 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737#endif
3738
3739 bool needWake;
3740 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003741 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003743 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3744 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3745 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 } // release lock
3747
3748 if (needWake) {
3749 mLooper->wake();
3750 }
3751}
3752
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003753/**
3754 * If one of the meta shortcuts is detected, process them here:
3755 * Meta + Backspace -> generate BACK
3756 * Meta + Enter -> generate HOME
3757 * This will potentially overwrite keyCode and metaState.
3758 */
3759void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003760 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003761 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3762 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3763 if (keyCode == AKEYCODE_DEL) {
3764 newKeyCode = AKEYCODE_BACK;
3765 } else if (keyCode == AKEYCODE_ENTER) {
3766 newKeyCode = AKEYCODE_HOME;
3767 }
3768 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003769 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003770 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003771 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003772 keyCode = newKeyCode;
3773 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3774 }
3775 } else if (action == AKEY_EVENT_ACTION_UP) {
3776 // In order to maintain a consistent stream of up and down events, check to see if the key
3777 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3778 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003779 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003780 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003781 auto replacementIt = mReplacedKeys.find(replacement);
3782 if (replacementIt != mReplacedKeys.end()) {
3783 keyCode = replacementIt->second;
3784 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003785 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3786 }
3787 }
3788}
3789
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3791#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3793 "policyFlags=0x%x, action=0x%x, "
3794 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3795 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3796 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3797 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798#endif
3799 if (!validateKeyEvent(args->action)) {
3800 return;
3801 }
3802
3803 uint32_t policyFlags = args->policyFlags;
3804 int32_t flags = args->flags;
3805 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003806 // InputDispatcher tracks and generates key repeats on behalf of
3807 // whatever notifies it, so repeatCount should always be set to 0
3808 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3810 policyFlags |= POLICY_FLAG_VIRTUAL;
3811 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 if (policyFlags & POLICY_FLAG_FUNCTION) {
3814 metaState |= AMETA_FUNCTION_ON;
3815 }
3816
3817 policyFlags |= POLICY_FLAG_TRUSTED;
3818
Michael Wright78f24442014-08-06 15:55:28 -07003819 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003820 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003821
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003823 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003824 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3825 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826
Michael Wright2b3c3302018-03-02 17:19:13 +00003827 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003829 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3830 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003831 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 bool needWake;
3835 { // acquire lock
3836 mLock.lock();
3837
3838 if (shouldSendKeyToInputFilterLocked(args)) {
3839 mLock.unlock();
3840
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003841 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3843 return; // event was consumed by the filter
3844 }
3845
3846 mLock.lock();
3847 }
3848
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003849 std::unique_ptr<KeyEntry> newEntry =
3850 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3851 args->displayId, policyFlags, args->action, flags,
3852 keyCode, args->scanCode, metaState, repeatCount,
3853 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003855 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 mLock.unlock();
3857 } // release lock
3858
3859 if (needWake) {
3860 mLooper->wake();
3861 }
3862}
3863
3864bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3865 return mInputFilterEnabled;
3866}
3867
3868void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3869#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003870 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3871 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003872 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3873 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003874 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003875 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3876 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3877 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3878 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 for (uint32_t i = 0; i < args->pointerCount; i++) {
3880 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003881 "x=%f, y=%f, pressure=%f, size=%f, "
3882 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3883 "orientation=%f",
3884 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3885 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3886 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3887 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3888 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3889 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3890 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3891 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3892 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3893 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 }
3895#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3897 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 return;
3899 }
3900
3901 uint32_t policyFlags = args->policyFlags;
3902 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003903
3904 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003905 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003906 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3907 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003908 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
3911 bool needWake;
3912 { // acquire lock
3913 mLock.lock();
3914
3915 if (shouldSendMotionToInputFilterLocked(args)) {
3916 mLock.unlock();
3917
3918 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003919 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003920 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3921 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003922 args->metaState, args->buttonState, args->classification, transform,
3923 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003924 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3925 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3926 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
3928 policyFlags |= POLICY_FLAG_FILTERED;
3929 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3930 return; // event was consumed by the filter
3931 }
3932
3933 mLock.lock();
3934 }
3935
3936 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003937 std::unique_ptr<MotionEntry> newEntry =
3938 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3939 args->source, args->displayId, policyFlags,
3940 args->action, args->actionButton, args->flags,
3941 args->metaState, args->buttonState,
3942 args->classification, args->edgeFlags,
3943 args->xPrecision, args->yPrecision,
3944 args->xCursorPosition, args->yCursorPosition,
3945 args->downTime, args->pointerCount,
3946 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947
Siarhei Vishniakouf9cb2a72021-07-09 03:22:42 +00003948 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3949 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3950 !mInputFilterEnabled) {
3951 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3952 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3953 }
3954
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003955 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 mLock.unlock();
3957 } // release lock
3958
3959 if (needWake) {
3960 mLooper->wake();
3961 }
3962}
3963
Chris Yef59a2f42020-10-16 12:55:26 -07003964void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3965#if DEBUG_INBOUND_EVENT_DETAILS
3966 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3967 " sensorType=%s",
3968 args->id, args->eventTime, args->deviceId, args->source,
3969 NamedEnum::string(args->sensorType).c_str());
3970#endif
3971
3972 bool needWake;
3973 { // acquire lock
3974 mLock.lock();
3975
3976 // Just enqueue a new sensor event.
3977 std::unique_ptr<SensorEntry> newEntry =
3978 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3979 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3980 args->sensorType, args->accuracy,
3981 args->accuracyChanged, args->values);
3982
3983 needWake = enqueueInboundEventLocked(std::move(newEntry));
3984 mLock.unlock();
3985 } // release lock
3986
3987 if (needWake) {
3988 mLooper->wake();
3989 }
3990}
3991
Chris Yefb552902021-02-03 17:18:37 -08003992void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3993#if DEBUG_INBOUND_EVENT_DETAILS
3994 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3995 args->deviceId, args->isOn);
3996#endif
3997 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3998}
3999
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004001 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002}
4003
4004void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
4005#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004006 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004007 "switchMask=0x%08x",
4008 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009#endif
4010
4011 uint32_t policyFlags = args->policyFlags;
4012 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004013 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014}
4015
4016void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
4017#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004018 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4019 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020#endif
4021
4022 bool needWake;
4023 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004024 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004026 std::unique_ptr<DeviceResetEntry> newEntry =
4027 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4028 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 } // release lock
4030
4031 if (needWake) {
4032 mLooper->wake();
4033 }
4034}
4035
Prabir Pradhan7e186182020-11-10 13:56:45 -08004036void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
4037#if DEBUG_INBOUND_EVENT_DETAILS
4038 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhanac483a62021-08-06 14:01:18 +00004039 args->request.enable ? "true" : "false");
Prabir Pradhan7e186182020-11-10 13:56:45 -08004040#endif
4041
Prabir Pradhan99987712020-11-10 18:43:05 -08004042 bool needWake;
4043 { // acquire lock
4044 std::scoped_lock _l(mLock);
4045 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhanac483a62021-08-06 14:01:18 +00004046 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004047 needWake = enqueueInboundEventLocked(std::move(entry));
4048 } // release lock
4049
4050 if (needWake) {
4051 mLooper->wake();
4052 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004053}
4054
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004055InputEventInjectionResult InputDispatcher::injectInputEvent(
4056 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4057 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058#if DEBUG_INBOUND_EVENT_DETAILS
4059 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004060 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4061 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004063 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064
4065 policyFlags |= POLICY_FLAG_INJECTED;
4066 if (hasInjectionPermission(injectorPid, injectorUid)) {
4067 policyFlags |= POLICY_FLAG_TRUSTED;
4068 }
4069
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004070 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004071 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4072 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4073 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4074 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4075 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004076 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004077 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004078 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004079 }
4080
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004084 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4085 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004087 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004090 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004091 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4092 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4093 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004094 int32_t keyCode = incomingKey.getKeyCode();
4095 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004096 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004098 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004099 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004100 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4101 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4102 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004104 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4105 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004106 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004107
4108 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4109 android::base::Timer t;
4110 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4111 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4112 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4113 std::to_string(t.duration().count()).c_str());
4114 }
4115 }
4116
4117 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118 std::unique_ptr<KeyEntry> injectedEntry =
4119 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004120 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004121 incomingKey.getDisplayId(), policyFlags, action,
4122 flags, keyCode, incomingKey.getScanCode(), metaState,
4123 incomingKey.getRepeatCount(),
4124 incomingKey.getDownTime());
4125 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004126 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 }
4128
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4131 int32_t action = motionEvent.getAction();
4132 size_t pointerCount = motionEvent.getPointerCount();
4133 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4134 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004135 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004136 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004138 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004139 }
4140
4141 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004142 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 android::base::Timer t;
4144 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4145 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4146 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4147 std::to_string(t.duration().count()).c_str());
4148 }
4149 }
4150
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004151 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4152 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4153 }
4154
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004156 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4157 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004158 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004159 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4160 resolvedDeviceId, motionEvent.getSource(),
4161 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004162 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004163 motionEvent.getButtonState(),
4164 motionEvent.getClassification(),
4165 motionEvent.getEdgeFlags(),
4166 motionEvent.getXPrecision(),
4167 motionEvent.getYPrecision(),
4168 motionEvent.getRawXCursorPosition(),
4169 motionEvent.getRawYCursorPosition(),
4170 motionEvent.getDownTime(), uint32_t(pointerCount),
4171 pointerProperties, samplePointerCoords,
4172 motionEvent.getXOffset(),
4173 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004174 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004175 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004176 sampleEventTimes += 1;
4177 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004178 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004179 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4180 resolvedDeviceId, motionEvent.getSource(),
4181 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004182 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004183 motionEvent.getMetaState(),
4184 motionEvent.getButtonState(),
4185 motionEvent.getClassification(),
4186 motionEvent.getEdgeFlags(),
4187 motionEvent.getXPrecision(),
4188 motionEvent.getYPrecision(),
4189 motionEvent.getRawXCursorPosition(),
4190 motionEvent.getRawYCursorPosition(),
4191 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004192 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004193 samplePointerCoords, motionEvent.getXOffset(),
4194 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004195 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 }
4197 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004201 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004202 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 }
4204
4205 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004206 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 injectionState->injectionIsAsync = true;
4208 }
4209
4210 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004211 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212
4213 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004214 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004215 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004216 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 }
4218
4219 mLock.unlock();
4220
4221 if (needWake) {
4222 mLooper->wake();
4223 }
4224
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004225 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004227 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004229 if (syncMode == InputEventInjectionSync::NONE) {
4230 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 } else {
4232 for (;;) {
4233 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004234 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 break;
4236 }
4237
4238 nsecs_t remainingTimeout = endTime - now();
4239 if (remainingTimeout <= 0) {
4240#if DEBUG_INJECTION
4241 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004244 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 break;
4246 }
4247
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004248 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 }
4250
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004251 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4252 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 while (injectionState->pendingForegroundDispatches != 0) {
4254#if DEBUG_INJECTION
4255 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004256 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257#endif
4258 nsecs_t remainingTimeout = endTime - now();
4259 if (remainingTimeout <= 0) {
4260#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4262 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004264 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 break;
4266 }
4267
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004268 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270 }
4271 }
4272
4273 injectionState->release();
4274 } // release lock
4275
4276#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004277 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279#endif
4280
4281 return injectionResult;
4282}
4283
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004284std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004285 std::array<uint8_t, 32> calculatedHmac;
4286 std::unique_ptr<VerifiedInputEvent> result;
4287 switch (event.getType()) {
4288 case AINPUT_EVENT_TYPE_KEY: {
4289 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4290 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4291 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004292 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004293 break;
4294 }
4295 case AINPUT_EVENT_TYPE_MOTION: {
4296 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4297 VerifiedMotionEvent verifiedMotionEvent =
4298 verifiedMotionEventFromMotionEvent(motionEvent);
4299 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004300 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004301 break;
4302 }
4303 default: {
4304 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4305 return nullptr;
4306 }
4307 }
4308 if (calculatedHmac == INVALID_HMAC) {
4309 return nullptr;
4310 }
4311 if (calculatedHmac != event.getHmac()) {
4312 return nullptr;
4313 }
4314 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004315}
4316
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 return injectorUid == 0 ||
4319 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320}
4321
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004322void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004324 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 if (injectionState) {
4326#if DEBUG_INJECTION
4327 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004328 "injectorPid=%d, injectorUid=%d",
4329 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330#endif
4331
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004332 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 // Log the outcome since the injector did not wait for the injection result.
4334 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004335 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 ALOGV("Asynchronous input event injection succeeded.");
4337 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004338 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339 ALOGW("Asynchronous input event injection failed.");
4340 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004341 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004342 ALOGW("Asynchronous input event injection permission denied.");
4343 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004345 ALOGW("Asynchronous input event injection timed out.");
4346 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004347 case InputEventInjectionResult::PENDING:
4348 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4349 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
4351 }
4352
4353 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004354 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 }
4356}
4357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004358void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4359 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 if (injectionState) {
4361 injectionState->pendingForegroundDispatches += 1;
4362 }
4363}
4364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4366 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 if (injectionState) {
4368 injectionState->pendingForegroundDispatches -= 1;
4369
4370 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004371 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 }
4373 }
4374}
4375
chaviw3277faf2021-05-19 16:45:23 -05004376const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004377 int32_t displayId) const {
chaviw3277faf2021-05-19 16:45:23 -05004378 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004379 auto it = mWindowHandlesByDisplay.find(displayId);
4380 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004381}
4382
chaviw3277faf2021-05-19 16:45:23 -05004383sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004384 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004385 if (windowHandleToken == nullptr) {
4386 return nullptr;
4387 }
4388
Arthur Hungb92218b2018-08-14 12:00:21 +08004389 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004390 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4391 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004392 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004393 return windowHandle;
4394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 }
4396 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004397 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398}
4399
chaviw3277faf2021-05-19 16:45:23 -05004400sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4401 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004402 if (windowHandleToken == nullptr) {
4403 return nullptr;
4404 }
4405
chaviw3277faf2021-05-19 16:45:23 -05004406 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004407 if (windowHandle->getToken() == windowHandleToken) {
4408 return windowHandle;
4409 }
4410 }
4411 return nullptr;
4412}
4413
chaviw3277faf2021-05-19 16:45:23 -05004414sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4415 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004416 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004417 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4418 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004419 if (handle->getId() == windowHandle->getId() &&
4420 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004421 if (windowHandle->getInfo()->displayId != it.first) {
4422 ALOGE("Found window %s in display %" PRId32
4423 ", but it should belong to display %" PRId32,
4424 windowHandle->getName().c_str(), it.first,
4425 windowHandle->getInfo()->displayId);
4426 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004427 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 }
4430 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004431 return nullptr;
4432}
4433
chaviw3277faf2021-05-19 16:45:23 -05004434sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004435 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4436 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437}
4438
chaviw3277faf2021-05-19 16:45:23 -05004439bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004440 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4441 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004442 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004443 if (connection != nullptr && noInputChannel) {
4444 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4445 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4446 return false;
4447 }
4448
4449 if (connection == nullptr) {
4450 if (!noInputChannel) {
4451 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4452 }
4453 return false;
4454 }
4455 if (!connection->responsive) {
4456 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4457 return false;
4458 }
4459 return true;
4460}
4461
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004462std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4463 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004464 auto connectionIt = mConnectionsByToken.find(token);
4465 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004466 return nullptr;
4467 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004468 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004469}
4470
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004471void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw3277faf2021-05-19 16:45:23 -05004472 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4473 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004474 // Remove all handles on a display if there are no windows left.
4475 mWindowHandlesByDisplay.erase(displayId);
4476 return;
4477 }
4478
4479 // Since we compare the pointer of input window handles across window updates, we need
4480 // to make sure the handle object for the same window stays unchanged across updates.
chaviw3277faf2021-05-19 16:45:23 -05004481 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4482 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4483 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004484 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004485 }
4486
chaviw3277faf2021-05-19 16:45:23 -05004487 std::vector<sp<WindowInfoHandle>> newHandles;
4488 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw3277faf2021-05-19 16:45:23 -05004489 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004490 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4491 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4492 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004493 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4494 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4495 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004496 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004497 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004498 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004499 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004500 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004501 }
4502
4503 if (info->displayId != displayId) {
4504 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4505 handle->getName().c_str(), displayId, info->displayId);
4506 continue;
4507 }
4508
Robert Carredd13602020-04-13 17:24:34 -07004509 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4510 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw3277faf2021-05-19 16:45:23 -05004511 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004512 oldHandle->updateFrom(handle);
4513 newHandles.push_back(oldHandle);
4514 } else {
4515 newHandles.push_back(handle);
4516 }
4517 }
4518
4519 // Insert or replace
4520 mWindowHandlesByDisplay[displayId] = newHandles;
4521}
4522
Arthur Hung72d8dc32020-03-28 00:48:39 +00004523void InputDispatcher::setInputWindows(
chaviw3277faf2021-05-19 16:45:23 -05004524 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004525 { // acquire lock
4526 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004527 for (const auto& [displayId, handles] : handlesPerDisplay) {
4528 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004529 }
4530 }
4531 // Wake up poll loop since it may need to make new input dispatching choices.
4532 mLooper->wake();
4533}
4534
Arthur Hungb92218b2018-08-14 12:00:21 +08004535/**
4536 * Called from InputManagerService, update window handle list by displayId that can receive input.
4537 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4538 * If set an empty list, remove all handles from the specific display.
4539 * For focused handle, check if need to change and send a cancel event to previous one.
4540 * For removed handle, check if need to send a cancel event if already in touch.
4541 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004542void InputDispatcher::setInputWindowsLocked(
chaviw3277faf2021-05-19 16:45:23 -05004543 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004544 if (DEBUG_FOCUS) {
4545 std::string windowList;
chaviw3277faf2021-05-19 16:45:23 -05004546 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004547 windowList += iwh->getName() + " ";
4548 }
4549 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004552 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw3277faf2021-05-19 16:45:23 -05004553 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004554 const bool noInputWindow =
chaviw3277faf2021-05-19 16:45:23 -05004555 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004556 if (noInputWindow && window->getToken() != nullptr) {
4557 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4558 window->getName().c_str());
4559 window->releaseChannel();
4560 }
4561 }
4562
Arthur Hung72d8dc32020-03-28 00:48:39 +00004563 // Copy old handles for release if they are no longer present.
chaviw3277faf2021-05-19 16:45:23 -05004564 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004566 // Save the old windows' orientation by ID before it gets updated.
4567 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw3277faf2021-05-19 16:45:23 -05004568 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004569 oldWindowOrientations.emplace(handle->getId(),
4570 handle->getInfo()->transform.getOrientation());
4571 }
4572
chaviw3277faf2021-05-19 16:45:23 -05004573 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004574
chaviw3277faf2021-05-19 16:45:23 -05004575 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004576 if (mLastHoverWindowHandle &&
4577 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4578 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004579 mLastHoverWindowHandle = nullptr;
4580 }
4581
Vishnu Nairc519ff72021-01-21 08:23:08 -08004582 std::optional<FocusResolver::FocusChanges> changes =
4583 mFocusResolver.setInputWindows(displayId, windowHandles);
4584 if (changes) {
4585 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004588 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4589 mTouchStatesByDisplay.find(displayId);
4590 if (stateIt != mTouchStatesByDisplay.end()) {
4591 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004592 for (size_t i = 0; i < state.windows.size();) {
4593 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004594 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004595 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004596 ALOGD("Touched window was removed: %s in display %" PRId32,
4597 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004598 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004599 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004600 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4601 if (touchedInputChannel != nullptr) {
4602 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4603 "touched window was removed");
4604 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606 state.windows.erase(state.windows.begin() + i);
4607 } else {
4608 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 }
4610 }
arthurhungb89ccb02020-12-30 16:19:01 +08004611
arthurhung6d4bed92021-03-17 11:59:33 +08004612 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004613 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004614 if (mDragState &&
4615 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004616 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004617 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004618 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004619 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004620
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004621 if (isPerWindowInputRotationEnabled()) {
4622 // Determine if the orientation of any of the input windows have changed, and cancel all
4623 // pointer events if necessary.
chaviw3277faf2021-05-19 16:45:23 -05004624 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4625 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004626 if (newWindowHandle != nullptr &&
4627 newWindowHandle->getInfo()->transform.getOrientation() !=
4628 oldWindowOrientations[oldWindowHandle->getId()]) {
4629 std::shared_ptr<InputChannel> inputChannel =
4630 getInputChannelLocked(newWindowHandle->getToken());
4631 if (inputChannel != nullptr) {
4632 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4633 "touched window's orientation changed");
4634 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4635 }
4636 }
4637 }
4638 }
4639
Arthur Hung72d8dc32020-03-28 00:48:39 +00004640 // Release information for windows that are no longer present.
4641 // This ensures that unused input channels are released promptly.
4642 // Otherwise, they might stick around until the window handle is destroyed
4643 // which might not happen until the next GC.
chaviw3277faf2021-05-19 16:45:23 -05004644 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004645 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004646 if (DEBUG_FOCUS) {
4647 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004648 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004649 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004650 // To avoid making too many calls into the compat framework, only
4651 // check for window flags when windows are going away.
4652 // TODO(b/157929241) : delete this. This is only needed temporarily
4653 // in order to gather some data about the flag usage
chaviw3277faf2021-05-19 16:45:23 -05004654 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004655 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4656 oldWindowHandle->getName().c_str());
4657 if (mCompatService != nullptr) {
4658 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4659 oldWindowHandle->getInfo()->ownerUid);
4660 }
4661 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004662 }
chaviw291d88a2019-02-14 10:33:58 -08004663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664}
4665
4666void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004667 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004668 if (DEBUG_FOCUS) {
4669 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4670 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4671 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004672 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004673 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004674 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 } // release lock
4676
4677 // Wake up poll loop since it may need to make new input dispatching choices.
4678 mLooper->wake();
4679}
4680
Vishnu Nair599f1412021-06-21 10:39:58 -07004681void InputDispatcher::setFocusedApplicationLocked(
4682 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4683 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4684 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4685
4686 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4687 return; // This application is already focused. No need to wake up or change anything.
4688 }
4689
4690 // Set the new application handle.
4691 if (inputApplicationHandle != nullptr) {
4692 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4693 } else {
4694 mFocusedApplicationHandlesByDisplay.erase(displayId);
4695 }
4696
4697 // No matter what the old focused application was, stop waiting on it because it is
4698 // no longer focused.
4699 resetNoFocusedWindowTimeoutLocked();
4700}
4701
Tiger Huang721e26f2018-07-24 22:26:19 +08004702/**
4703 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4704 * the display not specified.
4705 *
4706 * We track any unreleased events for each window. If a window loses the ability to receive the
4707 * released event, we will send a cancel event to it. So when the focused display is changed, we
4708 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4709 * display. The display-specified events won't be affected.
4710 */
4711void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004712 if (DEBUG_FOCUS) {
4713 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4714 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004715 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004716 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004717
4718 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004719 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004720 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004721 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004722 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004723 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004724 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725 CancelationOptions
4726 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4727 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004728 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004729 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4730 }
4731 }
4732 mFocusedDisplayId = displayId;
4733
Chris Ye3c2d6f52020-08-09 10:39:48 -07004734 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004735 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004736 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004737
Vishnu Nairad321cd2020-08-20 16:40:21 -07004738 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004739 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004740 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004741 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004742 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004743 }
4744 }
4745 }
4746
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004747 if (DEBUG_FOCUS) {
4748 logDispatchStateLocked();
4749 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004750 } // release lock
4751
4752 // Wake up poll loop since it may need to make new input dispatching choices.
4753 mLooper->wake();
4754}
4755
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004757 if (DEBUG_FOCUS) {
4758 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760
4761 bool changed;
4762 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004763 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764
4765 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4766 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004767 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 }
4769
4770 if (mDispatchEnabled && !enabled) {
4771 resetAndDropEverythingLocked("dispatcher is being disabled");
4772 }
4773
4774 mDispatchEnabled = enabled;
4775 mDispatchFrozen = frozen;
4776 changed = true;
4777 } else {
4778 changed = false;
4779 }
4780
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004781 if (DEBUG_FOCUS) {
4782 logDispatchStateLocked();
4783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 } // release lock
4785
4786 if (changed) {
4787 // Wake up poll loop since it may need to make new input dispatching choices.
4788 mLooper->wake();
4789 }
4790}
4791
4792void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004793 if (DEBUG_FOCUS) {
4794 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796
4797 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004798 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799
4800 if (mInputFilterEnabled == enabled) {
4801 return;
4802 }
4803
4804 mInputFilterEnabled = enabled;
4805 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4806 } // release lock
4807
4808 // Wake up poll loop since there might be work to do to drop everything.
4809 mLooper->wake();
4810}
4811
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004812void InputDispatcher::setInTouchMode(bool inTouchMode) {
4813 std::scoped_lock lock(mLock);
4814 mInTouchMode = inTouchMode;
4815}
4816
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004817void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4818 if (opacity < 0 || opacity > 1) {
4819 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4820 return;
4821 }
4822
4823 std::scoped_lock lock(mLock);
4824 mMaximumObscuringOpacityForTouch = opacity;
4825}
4826
4827void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4828 std::scoped_lock lock(mLock);
4829 mBlockUntrustedTouchesMode = mode;
4830}
4831
Arthur Hungabbb9d82021-09-01 14:52:30 +00004832std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4833 const sp<IBinder>& token) {
4834 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4835 for (TouchedWindow& w : state.windows) {
4836 if (w.windowHandle->getToken() == token) {
4837 return std::make_pair(&state, &w);
4838 }
4839 }
4840 }
4841 return std::make_pair(nullptr, nullptr);
4842}
4843
arthurhungb89ccb02020-12-30 16:19:01 +08004844bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4845 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004846 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004847 if (DEBUG_FOCUS) {
4848 ALOGD("Trivial transfer to same window.");
4849 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004850 return true;
4851 }
4852
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004854 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855
Arthur Hungabbb9d82021-09-01 14:52:30 +00004856 // Find the target touch state and touched window by fromToken.
4857 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4858 if (state == nullptr || touchedWindow == nullptr) {
4859 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 return false;
4861 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004862
4863 const int32_t displayId = state->displayId;
4864 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4865 if (toWindowHandle == nullptr) {
4866 ALOGW("Cannot transfer focus because to window not found.");
4867 return false;
4868 }
4869
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004870 if (DEBUG_FOCUS) {
4871 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00004872 touchedWindow->windowHandle->getName().c_str(),
4873 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 }
4875
Arthur Hungabbb9d82021-09-01 14:52:30 +00004876 // Erase old window.
4877 int32_t oldTargetFlags = touchedWindow->targetFlags;
4878 BitSet32 pointerIds = touchedWindow->pointerIds;
4879 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880
Arthur Hungabbb9d82021-09-01 14:52:30 +00004881 // Add new window.
4882 int32_t newTargetFlags = oldTargetFlags &
4883 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4884 InputTarget::FLAG_DISPATCH_AS_IS);
4885 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886
Arthur Hungabbb9d82021-09-01 14:52:30 +00004887 // Store the dragging window.
4888 if (isDragDrop) {
4889 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 }
4891
Arthur Hungabbb9d82021-09-01 14:52:30 +00004892 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004893 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4894 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004895 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004896 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004897 CancelationOptions
4898 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4899 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004901 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 }
4903
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004904 if (DEBUG_FOCUS) {
4905 logDispatchStateLocked();
4906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 } // release lock
4908
4909 // Wake up poll loop since it may need to make new input dispatching choices.
4910 mLooper->wake();
4911 return true;
4912}
4913
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004914// Binder call
4915bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4916 sp<IBinder> fromToken;
4917 { // acquire lock
4918 std::scoped_lock _l(mLock);
4919
Arthur Hungabbb9d82021-09-01 14:52:30 +00004920 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
4921 [](const auto& pair) { return pair.second.windows.size() == 1; });
4922 if (it == mTouchStatesByDisplay.end()) {
4923 ALOGW("Cannot transfer touch state because there is no exact window being touched");
4924 return false;
4925 }
4926 const int32_t displayId = it->first;
4927 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004928 if (toWindowHandle == nullptr) {
4929 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4930 return false;
4931 }
4932
Arthur Hungabbb9d82021-09-01 14:52:30 +00004933 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004934 const TouchedWindow& touchedWindow = state.windows[0];
4935 fromToken = touchedWindow.windowHandle->getToken();
4936 } // release lock
4937
4938 return transferTouchFocus(fromToken, destChannelToken);
4939}
4940
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004942 if (DEBUG_FOCUS) {
4943 ALOGD("Resetting and dropping all events (%s).", reason);
4944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945
4946 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4947 synthesizeCancelationEventsForAllConnectionsLocked(options);
4948
4949 resetKeyRepeatLocked();
4950 releasePendingEventLocked();
4951 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004952 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004954 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004955 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004957 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958}
4959
4960void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004961 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962 dumpDispatchStateLocked(dump);
4963
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004964 std::istringstream stream(dump);
4965 std::string line;
4966
4967 while (std::getline(stream, line, '\n')) {
4968 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 }
4970}
4971
Prabir Pradhan99987712020-11-10 18:43:05 -08004972std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4973 std::string dump;
4974
Prabir Pradhanac483a62021-08-06 14:01:18 +00004975 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
4976 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08004977
4978 std::string windowName = "None";
4979 if (mWindowTokenWithPointerCapture) {
chaviw3277faf2021-05-19 16:45:23 -05004980 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004981 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4982 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4983 : "token has capture without window";
4984 }
Prabir Pradhanac483a62021-08-06 14:01:18 +00004985 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08004986
4987 return dump;
4988}
4989
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004990void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004991 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4992 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4993 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004994 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995
Tiger Huang721e26f2018-07-24 22:26:19 +08004996 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4997 dump += StringPrintf(INDENT "FocusedApplications:\n");
4998 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4999 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005000 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005001 const std::chrono::duration timeout =
5002 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005003 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005004 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005005 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005008 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005010
Vishnu Nairc519ff72021-01-21 08:23:08 -08005011 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005012 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005014 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005015 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005016 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5017 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005018 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 state.displayId, toString(state.down), toString(state.split),
5020 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005021 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005022 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005023 for (size_t i = 0; i < state.windows.size(); i++) {
5024 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005025 dump += StringPrintf(INDENT4
5026 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5027 i, touchedWindow.windowHandle->getName().c_str(),
5028 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005029 }
5030 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005031 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005032 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005033 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005034 dump += INDENT3 "Portal windows:\n";
5035 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005036 const sp<WindowInfoHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005037 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5038 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005039 }
5040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 }
5042 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005043 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044 }
5045
arthurhung6d4bed92021-03-17 11:59:33 +08005046 if (mDragState) {
5047 dump += StringPrintf(INDENT "DragState:\n");
5048 mDragState->dump(dump, INDENT2);
5049 }
5050
Arthur Hungb92218b2018-08-14 12:00:21 +08005051 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005052 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05005053 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005054 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005055 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005056 dump += INDENT2 "Windows:\n";
5057 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005058 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5059 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005061 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005062 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005063 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005064 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005065 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005066 "applicationInfo.name=%s, "
5067 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005068 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005069 i, windowInfo->name.c_str(), windowInfo->id,
5070 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005071 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005072 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005073 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005074 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005075 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005076 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005077 windowInfo->frameLeft, windowInfo->frameTop,
5078 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005079 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005080 windowInfo->applicationInfo.name.c_str(),
5081 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005082 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005083 dump += StringPrintf(", inputFeatures=%s",
5084 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005085 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005086 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005087 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005088 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005089 millis(windowInfo->dispatchingTimeout),
5090 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005091 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005092 toString(windowInfo->touchOcclusionMode).c_str(),
5093 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005094 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005095 }
5096 } else {
5097 dump += INDENT2 "Windows: <none>\n";
5098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 }
5100 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005101 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 }
5103
Michael Wright3dd60e22019-03-27 22:06:44 +00005104 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005105 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005106 const std::vector<Monitor>& monitors = it.second;
5107 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5108 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005109 }
5110 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005111 const std::vector<Monitor>& monitors = it.second;
5112 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5113 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005116 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 }
5118
5119 nsecs_t currentTime = now();
5120
5121 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005122 if (!mRecentQueue.empty()) {
5123 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005124 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005125 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005126 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005127 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 }
5129 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005130 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 }
5132
5133 // Dump event currently being dispatched.
5134 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005135 dump += INDENT "PendingEvent:\n";
5136 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005137 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005138 dump += StringPrintf(", age=%" PRId64 "ms\n",
5139 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005141 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 }
5143
5144 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005145 if (!mInboundQueue.empty()) {
5146 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005147 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005148 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005149 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005150 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 }
5152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005153 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005156 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005157 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005158 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5159 const KeyReplacement& replacement = pair.first;
5160 int32_t newKeyCode = pair.second;
5161 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005162 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005163 }
5164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005166 }
5167
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005168 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005169 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005170 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005171 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005172 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005173 connection->inputChannel->getFd().get(),
5174 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005175 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005176 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005178 if (!connection->outboundQueue.empty()) {
5179 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5180 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005181 dump += dumpQueue(connection->outboundQueue, currentTime);
5182
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005184 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 }
5186
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005187 if (!connection->waitQueue.empty()) {
5188 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5189 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005190 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005192 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 }
5194 }
5195 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005196 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 }
5198
5199 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005200 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5201 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005203 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005204 }
5205
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005206 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005207 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5208 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5209 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005210 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005211 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212}
5213
Michael Wright3dd60e22019-03-27 22:06:44 +00005214void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5215 const size_t numMonitors = monitors.size();
5216 for (size_t i = 0; i < numMonitors; i++) {
5217 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005218 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005219 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5220 dump += "\n";
5221 }
5222}
5223
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005224class LooperEventCallback : public LooperCallback {
5225public:
5226 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5227 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5228
5229private:
5230 std::function<int(int events)> mCallback;
5231};
5232
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005233Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005234#if DEBUG_CHANNEL_CREATION
5235 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236#endif
5237
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005238 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005239 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005240 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005241
5242 if (result) {
5243 return base::Error(result) << "Failed to open input channel pair with name " << name;
5244 }
5245
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005247 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005248 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005249 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005250 sp<Connection> connection =
5251 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005253 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5254 ALOGE("Created a new connection, but the token %p is already known", token.get());
5255 }
5256 mConnectionsByToken.emplace(token, connection);
5257
5258 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5259 this, std::placeholders::_1, token);
5260
5261 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 } // release lock
5263
5264 // Wake the looper because some connections have changed.
5265 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005266 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267}
5268
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005269Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5270 bool isGestureMonitor,
5271 const std::string& name,
5272 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005273 std::shared_ptr<InputChannel> serverChannel;
5274 std::unique_ptr<InputChannel> clientChannel;
5275 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5276 if (result) {
5277 return base::Error(result) << "Failed to open input channel pair with name " << name;
5278 }
5279
Michael Wright3dd60e22019-03-27 22:06:44 +00005280 { // acquire lock
5281 std::scoped_lock _l(mLock);
5282
5283 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005284 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5285 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005286 }
5287
Garfield Tan15601662020-09-22 15:32:38 -07005288 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005289 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005290 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005291
5292 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5293 ALOGE("Created a new connection, but the token %p is already known", token.get());
5294 }
5295 mConnectionsByToken.emplace(token, connection);
5296 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5297 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005298
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005299 auto& monitorsByDisplay =
5300 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005301 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005302
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005303 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005304 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5305 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005306 }
Garfield Tan15601662020-09-22 15:32:38 -07005307
Michael Wright3dd60e22019-03-27 22:06:44 +00005308 // Wake the looper because some connections have changed.
5309 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005310 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005311}
5312
Garfield Tan15601662020-09-22 15:32:38 -07005313status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005315 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
Garfield Tan15601662020-09-22 15:32:38 -07005317 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 if (status) {
5319 return status;
5320 }
5321 } // release lock
5322
5323 // Wake the poll loop because removing the connection may have changed the current
5324 // synchronization state.
5325 mLooper->wake();
5326 return OK;
5327}
5328
Garfield Tan15601662020-09-22 15:32:38 -07005329status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5330 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005331 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005332 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005333 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 return BAD_VALUE;
5335 }
5336
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005337 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005338
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005340 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 }
5342
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005343 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344
5345 nsecs_t currentTime = now();
5346 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5347
5348 connection->status = Connection::STATUS_ZOMBIE;
5349 return OK;
5350}
5351
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005352void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5353 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5354 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005355}
5356
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005357void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005358 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005359 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005360 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005361 std::vector<Monitor>& monitors = it->second;
5362 const size_t numMonitors = monitors.size();
5363 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005364 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005365 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5366 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005367 monitors.erase(monitors.begin() + i);
5368 break;
5369 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005370 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005371 if (monitors.empty()) {
5372 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005373 } else {
5374 ++it;
5375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 }
5377}
5378
Michael Wright3dd60e22019-03-27 22:06:44 +00005379status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5380 { // acquire lock
5381 std::scoped_lock _l(mLock);
5382 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5383
5384 if (!foundDisplayId) {
5385 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5386 return BAD_VALUE;
5387 }
5388 int32_t displayId = foundDisplayId.value();
5389
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005390 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5391 mTouchStatesByDisplay.find(displayId);
5392 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005393 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5394 return BAD_VALUE;
5395 }
5396
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005397 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005398 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005399 std::optional<int32_t> foundDeviceId;
5400 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005401 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005402 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005403 foundDeviceId = state.deviceId;
5404 }
5405 }
5406 if (!foundDeviceId || !state.down) {
5407 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005408 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005409 return BAD_VALUE;
5410 }
5411 int32_t deviceId = foundDeviceId.value();
5412
5413 // Send cancel events to all the input channels we're stealing from.
5414 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005415 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005416 options.deviceId = deviceId;
5417 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005418 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005419 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005420 std::shared_ptr<InputChannel> channel =
5421 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005422 if (channel != nullptr) {
5423 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005424 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005425 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005426 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005427 canceledWindows += "]";
5428 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5429 canceledWindows.c_str());
5430
Michael Wright3dd60e22019-03-27 22:06:44 +00005431 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hung71625472021-11-16 02:45:54 +00005432 state.split = false;
Michael Wright3dd60e22019-03-27 22:06:44 +00005433 state.filterNonMonitors();
5434 }
5435 return OK;
5436}
5437
Prabir Pradhan99987712020-11-10 18:43:05 -08005438void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5439 { // acquire lock
5440 std::scoped_lock _l(mLock);
5441 if (DEBUG_FOCUS) {
chaviw3277faf2021-05-19 16:45:23 -05005442 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005443 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5444 windowHandle != nullptr ? windowHandle->getName().c_str()
5445 : "token without window");
5446 }
5447
Vishnu Nairc519ff72021-01-21 08:23:08 -08005448 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005449 if (focusedToken != windowToken) {
5450 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5451 enabled ? "enable" : "disable");
5452 return;
5453 }
5454
Prabir Pradhanac483a62021-08-06 14:01:18 +00005455 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005456 ALOGW("Ignoring request to %s Pointer Capture: "
5457 "window has %s requested pointer capture.",
5458 enabled ? "enable" : "disable", enabled ? "already" : "not");
5459 return;
5460 }
5461
Prabir Pradhan99987712020-11-10 18:43:05 -08005462 setPointerCaptureLocked(enabled);
5463 } // release lock
5464
5465 // Wake the thread to process command entries.
5466 mLooper->wake();
5467}
5468
Michael Wright3dd60e22019-03-27 22:06:44 +00005469std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5470 const sp<IBinder>& token) {
5471 for (const auto& it : mGestureMonitorsByDisplay) {
5472 const std::vector<Monitor>& monitors = it.second;
5473 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005474 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005475 return it.first;
5476 }
5477 }
5478 }
5479 return std::nullopt;
5480}
5481
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005482std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5483 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5484 if (gesturePid.has_value()) {
5485 return gesturePid;
5486 }
5487 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5488}
5489
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005490sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005491 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005492 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005493 }
5494
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005495 for (const auto& [token, connection] : mConnectionsByToken) {
5496 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005497 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 }
5499 }
Robert Carr4e670e52018-08-15 13:26:12 -07005500
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005501 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502}
5503
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005504std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5505 sp<Connection> connection = getConnectionLocked(connectionToken);
5506 if (connection == nullptr) {
5507 return "<nullptr>";
5508 }
5509 return connection->getInputChannelName();
5510}
5511
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005512void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005513 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005514 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005515}
5516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005517void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5518 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005519 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005520 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5521 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 commandEntry->connection = connection;
5523 commandEntry->eventTime = currentTime;
5524 commandEntry->seq = seq;
5525 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005526 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005527 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528}
5529
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005530void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5531 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005533 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005535 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5536 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005538 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539}
5540
Vishnu Nairad321cd2020-08-20 16:40:21 -07005541void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5542 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005543 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5544 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005545 commandEntry->oldToken = oldToken;
5546 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005547 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005548}
5549
arthurhungf452d0b2021-01-06 00:19:52 +08005550void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5551 std::unique_ptr<CommandEntry> commandEntry =
5552 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5553 commandEntry->newToken = token;
5554 commandEntry->x = x;
5555 commandEntry->y = y;
5556 postCommandLocked(std::move(commandEntry));
5557}
5558
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005559void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5560 if (connection == nullptr) {
5561 LOG_ALWAYS_FATAL("Caller must check for nullness");
5562 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005563 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5564 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005565 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005566 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005567 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005568 return;
5569 }
5570 /**
5571 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5572 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5573 * has changed. This could cause newer entries to time out before the already dispatched
5574 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5575 * processes the events linearly. So providing information about the oldest entry seems to be
5576 * most useful.
5577 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005578 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005579 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5580 std::string reason =
5581 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005582 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005583 ns2ms(currentWait),
5584 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005585 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005586 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005587
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005588 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5589
5590 // Stop waking up for events on this connection, it is already unresponsive
5591 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005592}
5593
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005594void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5595 std::string reason =
5596 StringPrintf("%s does not have a focused window", application->getName().c_str());
5597 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005598
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005599 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5600 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5601 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005602 postCommandLocked(std::move(commandEntry));
5603}
5604
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005605void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5606 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5607 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5608 commandEntry->obscuringPackage = obscuringPackage;
5609 postCommandLocked(std::move(commandEntry));
5610}
5611
chaviw3277faf2021-05-19 16:45:23 -05005612void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005613 const std::string& reason) {
5614 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5615 updateLastAnrStateLocked(windowLabel, reason);
5616}
5617
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005618void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5619 const std::string& reason) {
5620 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005621 updateLastAnrStateLocked(windowLabel, reason);
5622}
5623
5624void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5625 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005627 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 struct tm tm;
5629 localtime_r(&t, &tm);
5630 char timestr[64];
5631 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005632 mLastAnrState.clear();
5633 mLastAnrState += INDENT "ANR:\n";
5634 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005635 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5636 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005637 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638}
5639
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005640void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 mLock.unlock();
5642
5643 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5644
5645 mLock.lock();
5646}
5647
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005648void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 sp<Connection> connection = commandEntry->connection;
5650
5651 if (connection->status != Connection::STATUS_ZOMBIE) {
5652 mLock.unlock();
5653
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005654 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655
5656 mLock.lock();
5657 }
5658}
5659
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005660void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005661 sp<IBinder> oldToken = commandEntry->oldToken;
5662 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005663 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005664 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005665 mLock.lock();
5666}
5667
arthurhungf452d0b2021-01-06 00:19:52 +08005668void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5669 sp<IBinder> newToken = commandEntry->newToken;
5670 mLock.unlock();
5671 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5672 mLock.lock();
5673}
5674
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005675void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005677
5678 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5679
5680 mLock.lock();
5681}
5682
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005683void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005684 mLock.unlock();
5685
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005686 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687
5688 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005689}
5690
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005691void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005692 mLock.unlock();
5693
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005694 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5695
5696 mLock.lock();
5697}
5698
5699void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5700 mLock.unlock();
5701
5702 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5703
5704 mLock.lock();
5705}
5706
5707void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5708 mLock.unlock();
5709
5710 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005711
5712 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005713}
5714
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005715void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5716 mLock.unlock();
5717
5718 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5719
5720 mLock.lock();
5721}
5722
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5724 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005725 KeyEntry& entry = *(commandEntry->keyEntry);
5726 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727
5728 mLock.unlock();
5729
Michael Wright2b3c3302018-03-02 17:19:13 +00005730 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005731 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005732 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005733 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5734 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005735 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737
5738 mLock.lock();
5739
5740 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005741 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005743 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005745 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5746 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748}
5749
chaviwfd6d3512019-03-25 13:23:49 -07005750void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5751 mLock.unlock();
5752 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5753 mLock.lock();
5754}
5755
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005756/**
5757 * Connection is responsive if it has no events in the waitQueue that are older than the
5758 * current time.
5759 */
5760static bool isConnectionResponsive(const Connection& connection) {
5761 const nsecs_t currentTime = now();
5762 for (const DispatchEntry* entry : connection.waitQueue) {
5763 if (entry->timeoutTime < currentTime) {
5764 return false;
5765 }
5766 }
5767 return true;
5768}
5769
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005770void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005772 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005774 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775
5776 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005777 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005778 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005779 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005781 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005782 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005783 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005784 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5785 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005786 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005787 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5788 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5789 connection->inputChannel->getConnectionToken(),
5790 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5791 finishTime);
5792 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005793
5794 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005795 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005796 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005797 restartEvent =
5798 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005799 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005800 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005801 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5802 handled);
5803 } else {
5804 restartEvent = false;
5805 }
5806
5807 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005808 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005809 // contents of the wait queue to have been drained, so we need to double-check
5810 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005811 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5812 if (dispatchEntryIt != connection->waitQueue.end()) {
5813 dispatchEntry = *dispatchEntryIt;
5814 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005815 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5816 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005817 if (!connection->responsive) {
5818 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005819 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005820 // The connection was unresponsive, and now it's responsive.
5821 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005822 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005823 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005824 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005825 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005826 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005827 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005828 } else {
5829 releaseDispatchEntry(dispatchEntry);
5830 }
5831 }
5832
5833 // Start the next dispatch cycle for this connection.
5834 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835}
5836
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005837void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5838 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5839 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5840 monitorUnresponsiveCommand->pid = pid;
5841 monitorUnresponsiveCommand->reason = std::move(reason);
5842 postCommandLocked(std::move(monitorUnresponsiveCommand));
5843}
5844
5845void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5846 std::string reason) {
5847 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5848 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5849 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5850 windowUnresponsiveCommand->reason = std::move(reason);
5851 postCommandLocked(std::move(windowUnresponsiveCommand));
5852}
5853
5854void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5855 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5856 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5857 monitorResponsiveCommand->pid = pid;
5858 postCommandLocked(std::move(monitorResponsiveCommand));
5859}
5860
5861void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5862 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5863 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5864 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5865 postCommandLocked(std::move(windowResponsiveCommand));
5866}
5867
5868/**
5869 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5870 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5871 * command entry to the command queue.
5872 */
5873void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5874 std::string reason) {
5875 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5876 if (connection.monitor) {
5877 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5878 reason.c_str());
5879 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5880 if (!pid.has_value()) {
5881 ALOGE("Could not find unresponsive monitor for connection %s",
5882 connection.inputChannel->getName().c_str());
5883 return;
5884 }
5885 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5886 return;
5887 }
5888 // If not a monitor, must be a window
5889 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5890 reason.c_str());
5891 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5892}
5893
5894/**
5895 * Tell the policy that a connection has become responsive so that it can stop ANR.
5896 */
5897void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5898 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5899 if (connection.monitor) {
5900 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5901 if (!pid.has_value()) {
5902 ALOGE("Could not find responsive monitor for connection %s",
5903 connection.inputChannel->getName().c_str());
5904 return;
5905 }
5906 sendMonitorResponsiveCommandLocked(pid.value());
5907 return;
5908 }
5909 // If not a monitor, must be a window
5910 sendWindowResponsiveCommandLocked(connectionToken);
5911}
5912
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005914 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005915 KeyEntry& keyEntry, bool handled) {
5916 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005917 if (!handled) {
5918 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005919 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005920 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005921 return false;
5922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005924 // Get the fallback key state.
5925 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005926 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005927 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005928 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005929 connection->inputState.removeFallbackKey(originalKeyCode);
5930 }
5931
5932 if (handled || !dispatchEntry->hasForegroundTarget()) {
5933 // If the application handles the original key for which we previously
5934 // generated a fallback or if the window is not a foreground window,
5935 // then cancel the associated fallback key, if any.
5936 if (fallbackKeyCode != -1) {
5937 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005939 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005940 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005941 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005943 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005944 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945
5946 mLock.unlock();
5947
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005948 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005949 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950
5951 mLock.lock();
5952
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005953 // Cancel the fallback key.
5954 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956 "application handled the original non-fallback key "
5957 "or is no longer a foreground target, "
5958 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959 options.keyCode = fallbackKeyCode;
5960 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005962 connection->inputState.removeFallbackKey(originalKeyCode);
5963 }
5964 } else {
5965 // If the application did not handle a non-fallback key, first check
5966 // that we are in a good state to perform unhandled key event processing
5967 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005968 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005969 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005971 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005972 "since this is not an initial down. "
5973 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005974 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976 return false;
5977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005979 // Dispatch the unhandled key to the policy.
5980#if DEBUG_OUTBOUND_EVENT_DETAILS
5981 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005982 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005983 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005984#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005985 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005986
5987 mLock.unlock();
5988
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005989 bool fallback =
5990 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005991 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005992
5993 mLock.lock();
5994
5995 if (connection->status != Connection::STATUS_NORMAL) {
5996 connection->inputState.removeFallbackKey(originalKeyCode);
5997 return false;
5998 }
5999
6000 // Latch the fallback keycode for this key on an initial down.
6001 // The fallback keycode cannot change at any other point in the lifecycle.
6002 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006004 fallbackKeyCode = event.getKeyCode();
6005 } else {
6006 fallbackKeyCode = AKEYCODE_UNKNOWN;
6007 }
6008 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6009 }
6010
6011 ALOG_ASSERT(fallbackKeyCode != -1);
6012
6013 // Cancel the fallback key if the policy decides not to send it anymore.
6014 // We will continue to dispatch the key to the policy but we will no
6015 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006016 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6017 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018#if DEBUG_OUTBOUND_EVENT_DETAILS
6019 if (fallback) {
6020 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006021 "as a fallback for %d, but on the DOWN it had requested "
6022 "to send %d instead. Fallback canceled.",
6023 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006024 } else {
6025 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006026 "but on the DOWN it had requested to send %d. "
6027 "Fallback canceled.",
6028 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006029 }
6030#endif
6031
6032 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6033 "canceling fallback, policy no longer desires it");
6034 options.keyCode = fallbackKeyCode;
6035 synthesizeCancelationEventsForConnectionLocked(connection, options);
6036
6037 fallback = false;
6038 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006039 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006040 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006041 }
6042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043
6044#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006045 {
6046 std::string msg;
6047 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6048 connection->inputState.getFallbackKeys();
6049 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006050 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006052 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006053 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 }
6055#endif
6056
6057 if (fallback) {
6058 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006059 keyEntry.eventTime = event.getEventTime();
6060 keyEntry.deviceId = event.getDeviceId();
6061 keyEntry.source = event.getSource();
6062 keyEntry.displayId = event.getDisplayId();
6063 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6064 keyEntry.keyCode = fallbackKeyCode;
6065 keyEntry.scanCode = event.getScanCode();
6066 keyEntry.metaState = event.getMetaState();
6067 keyEntry.repeatCount = event.getRepeatCount();
6068 keyEntry.downTime = event.getDownTime();
6069 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006070
6071#if DEBUG_OUTBOUND_EVENT_DETAILS
6072 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006073 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006074 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006075#endif
6076 return true; // restart the event
6077 } else {
6078#if DEBUG_OUTBOUND_EVENT_DETAILS
6079 ALOGD("Unhandled key event: No fallback key.");
6080#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006081
6082 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006083 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084 }
6085 }
6086 return false;
6087}
6088
6089bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006090 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006091 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 return false;
6093}
6094
6095void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6096 mLock.unlock();
6097
Sean Stoutb4e0a592021-02-23 07:34:53 -08006098 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6099 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100
6101 mLock.lock();
6102}
6103
Michael Wrightd02c5b62014-02-10 15:10:22 -08006104void InputDispatcher::traceInboundQueueLengthLocked() {
6105 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006106 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107 }
6108}
6109
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006110void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 if (ATRACE_ENABLED()) {
6112 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006113 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6114 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006115 }
6116}
6117
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006118void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 if (ATRACE_ENABLED()) {
6120 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006121 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6122 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 }
6124}
6125
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006126void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006127 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006129 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130 dumpDispatchStateLocked(dump);
6131
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006132 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006133 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006134 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006135 }
6136}
6137
6138void InputDispatcher::monitor() {
6139 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006140 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006142 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006143}
6144
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006145/**
6146 * Wake up the dispatcher and wait until it processes all events and commands.
6147 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6148 * this method can be safely called from any thread, as long as you've ensured that
6149 * the work you are interested in completing has already been queued.
6150 */
6151bool InputDispatcher::waitForIdle() {
6152 /**
6153 * Timeout should represent the longest possible time that a device might spend processing
6154 * events and commands.
6155 */
6156 constexpr std::chrono::duration TIMEOUT = 100ms;
6157 std::unique_lock lock(mLock);
6158 mLooper->wake();
6159 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6160 return result == std::cv_status::no_timeout;
6161}
6162
Vishnu Naire798b472020-07-23 13:52:21 -07006163/**
6164 * Sets focus to the window identified by the token. This must be called
6165 * after updating any input window handles.
6166 *
6167 * Params:
6168 * request.token - input channel token used to identify the window that should gain focus.
6169 * request.focusedToken - the token that the caller expects currently to be focused. If the
6170 * specified token does not match the currently focused window, this request will be dropped.
6171 * If the specified focused token matches the currently focused window, the call will succeed.
6172 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6173 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6174 * when requesting the focus change. This determines which request gets
6175 * precedence if there is a focus change request from another source such as pointer down.
6176 */
Vishnu Nair958da932020-08-21 17:12:37 -07006177void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6178 { // acquire lock
6179 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006180 std::optional<FocusResolver::FocusChanges> changes =
6181 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6182 if (changes) {
6183 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006184 }
6185 } // release lock
6186 // Wake up poll loop since it may need to make new input dispatching choices.
6187 mLooper->wake();
6188}
6189
Vishnu Nairc519ff72021-01-21 08:23:08 -08006190void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6191 if (changes.oldFocus) {
6192 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006193 if (focusedInputChannel) {
6194 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6195 "focus left window");
6196 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006197 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006198 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006199 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006200 if (changes.newFocus) {
6201 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006202 }
6203
Prabir Pradhan99987712020-11-10 18:43:05 -08006204 // If a window has pointer capture, then it must have focus. We need to ensure that this
6205 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6206 // If the window loses focus before it loses pointer capture, then the window can be in a state
6207 // where it has pointer capture but not focus, violating the contract. Therefore we must
6208 // dispatch the pointer capture event before the focus event. Since focus events are added to
6209 // the front of the queue (above), we add the pointer capture event to the front of the queue
6210 // after the focus events are added. This ensures the pointer capture event ends up at the
6211 // front.
6212 disablePointerCaptureForcedLocked();
6213
Vishnu Nairc519ff72021-01-21 08:23:08 -08006214 if (mFocusedDisplayId == changes.displayId) {
6215 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006216 }
6217}
Vishnu Nair958da932020-08-21 17:12:37 -07006218
Prabir Pradhan99987712020-11-10 18:43:05 -08006219void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhanac483a62021-08-06 14:01:18 +00006220 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006221 return;
6222 }
6223
6224 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6225
Prabir Pradhanac483a62021-08-06 14:01:18 +00006226 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006227 setPointerCaptureLocked(false);
6228 }
6229
6230 if (!mWindowTokenWithPointerCapture) {
6231 // No need to send capture changes because no window has capture.
6232 return;
6233 }
6234
6235 if (mPendingEvent != nullptr) {
6236 // Move the pending event to the front of the queue. This will give the chance
6237 // for the pending event to be dropped if it is a captured event.
6238 mInboundQueue.push_front(mPendingEvent);
6239 mPendingEvent = nullptr;
6240 }
6241
6242 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhanac483a62021-08-06 14:01:18 +00006243 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006244 mInboundQueue.push_front(std::move(entry));
6245}
6246
Prabir Pradhan99987712020-11-10 18:43:05 -08006247void InputDispatcher::setPointerCaptureLocked(bool enabled) {
Prabir Pradhanac483a62021-08-06 14:01:18 +00006248 mCurrentPointerCaptureRequest.enable = enabled;
6249 mCurrentPointerCaptureRequest.seq++;
Prabir Pradhan99987712020-11-10 18:43:05 -08006250 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6251 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
Prabir Pradhanac483a62021-08-06 14:01:18 +00006252 commandEntry->pointerCaptureRequest = mCurrentPointerCaptureRequest;
Prabir Pradhan99987712020-11-10 18:43:05 -08006253 postCommandLocked(std::move(commandEntry));
6254}
6255
6256void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6257 android::inputdispatcher::CommandEntry* commandEntry) {
6258 mLock.unlock();
6259
Prabir Pradhanac483a62021-08-06 14:01:18 +00006260 mPolicy->setPointerCapture(commandEntry->pointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006261
6262 mLock.lock();
6263}
6264
Vishnu Nair599f1412021-06-21 10:39:58 -07006265void InputDispatcher::displayRemoved(int32_t displayId) {
6266 { // acquire lock
6267 std::scoped_lock _l(mLock);
6268 // Set an empty list to remove all handles from the specific display.
6269 setInputWindowsLocked(/* window handles */ {}, displayId);
6270 setFocusedApplicationLocked(displayId, nullptr);
6271 // Call focus resolver to clean up stale requests. This must be called after input windows
6272 // have been removed for the removed display.
6273 mFocusResolver.displayRemoved(displayId);
6274 } // release lock
6275
6276 // Wake up poll loop since it may need to make new input dispatching choices.
6277 mLooper->wake();
6278}
6279
chaviw15fab6f2021-06-07 14:15:52 -05006280void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6281 // The listener sends the windows as a flattened array. Separate the windows by display for
6282 // more convenient parsing.
6283 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6284
6285 for (const auto& info : windowInfos) {
6286 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6287 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6288 }
6289 setInputWindows(handlesPerDisplay);
6290}
6291
Vishnu Nair41f77b82021-09-03 16:07:44 -07006292bool InputDispatcher::shouldDropInput(
6293 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6294 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6295 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6296 isWindowObscuredLocked(windowHandle))) {
6297 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6298 "%" PRId32 ".",
6299 NamedEnum::string(entry.type).c_str(), windowHandle->getName().c_str(),
6300 windowHandle->getInfo()->inputFeatures.string().c_str(),
6301 windowHandle->getInfo()->displayId);
6302 return true;
6303 }
6304 return false;
6305}
6306
Garfield Tane84e6f92019-08-29 17:28:41 -07006307} // namespace android::inputdispatcher