blob: aa667803dd47c52e00fd6f86d0f67d0b71fb4075 [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 =
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700101 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
102
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 mFocusedWindowRequestedPointerCapture(false),
536 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000537 mLatencyAggregator(),
538 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000539 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800541 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542
Yi Kong9b14ac62018-07-17 13:48:38 -0700543 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544
545 policy->getDispatcherConfiguration(&mConfig);
546}
547
548InputDispatcher::~InputDispatcher() {
549 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800550 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551
552 resetKeyRepeatLocked();
553 releasePendingEventLocked();
554 drainInboundQueueLocked();
555 }
556
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000557 while (!mConnectionsByToken.empty()) {
558 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700559 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 }
561}
562
chaviw15fab6f2021-06-07 14:15:52 -0500563void InputDispatcher::onFirstRef() {
564 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
565}
566
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700567status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700568 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700569 return ALREADY_EXISTS;
570 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700571 mThread = std::make_unique<InputThread>(
572 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
573 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700574}
575
576status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700577 if (mThread && mThread->isCallingThread()) {
578 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700579 return INVALID_OPERATION;
580 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700581 mThread.reset();
582 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700583}
584
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585void InputDispatcher::dispatchOnce() {
586 nsecs_t nextWakeupTime = LONG_LONG_MAX;
587 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800588 std::scoped_lock _l(mLock);
589 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590
591 // Run a dispatch loop if there are no pending commands.
592 // The dispatch loop might enqueue commands to run afterwards.
593 if (!haveCommandsLocked()) {
594 dispatchOnceInnerLocked(&nextWakeupTime);
595 }
596
597 // Run all pending commands if there are any.
598 // If any commands were run then force the next poll to wake up immediately.
599 if (runCommandsLockedInterruptible()) {
600 nextWakeupTime = LONG_LONG_MIN;
601 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800602
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700603 // If we are still waiting for ack on some events,
604 // we might have to wake up earlier to check if an app is anr'ing.
605 const nsecs_t nextAnrCheck = processAnrsLocked();
606 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
607
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800608 // We are about to enter an infinitely long sleep, because we have no commands or
609 // pending or queued events
610 if (nextWakeupTime == LONG_LONG_MAX) {
611 mDispatcherEnteredIdle.notify_all();
612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 } // release lock
614
615 // Wait for callback or timeout or wake. (make sure we round up, not down)
616 nsecs_t currentTime = now();
617 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
618 mLooper->pollOnce(timeoutMillis);
619}
620
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700621/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500622 * Raise ANR if there is no focused window.
623 * Before the ANR is raised, do a final state check:
624 * 1. The currently focused application must be the same one we are waiting for.
625 * 2. Ensure we still don't have a focused window.
626 */
627void InputDispatcher::processNoFocusedWindowAnrLocked() {
628 // Check if the application that we are waiting for is still focused.
629 std::shared_ptr<InputApplicationHandle> focusedApplication =
630 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
631 if (focusedApplication == nullptr ||
632 focusedApplication->getApplicationToken() !=
633 mAwaitedFocusedApplication->getApplicationToken()) {
634 // Unexpected because we should have reset the ANR timer when focused application changed
635 ALOGE("Waited for a focused window, but focused application has already changed to %s",
636 focusedApplication->getName().c_str());
637 return; // The focused application has changed.
638 }
639
chaviw3277faf2021-05-19 16:45:23 -0500640 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500641 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
642 if (focusedWindowHandle != nullptr) {
643 return; // We now have a focused window. No need for ANR.
644 }
645 onAnrLocked(mAwaitedFocusedApplication);
646}
647
648/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700649 * Check if any of the connections' wait queues have events that are too old.
650 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
651 * Return the time at which we should wake up next.
652 */
653nsecs_t InputDispatcher::processAnrsLocked() {
654 const nsecs_t currentTime = now();
655 nsecs_t nextAnrCheck = LONG_LONG_MAX;
656 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
657 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
658 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500659 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700660 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500661 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700662 return LONG_LONG_MIN;
663 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500664 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700665 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
666 }
667 }
668
669 // Check if any connection ANRs are due
670 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
671 if (currentTime < nextAnrCheck) { // most likely scenario
672 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
673 }
674
675 // If we reached here, we have an unresponsive connection.
676 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
677 if (connection == nullptr) {
678 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
679 return nextAnrCheck;
680 }
681 connection->responsive = false;
682 // Stop waking up for this unresponsive connection
683 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000684 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700685 return LONG_LONG_MIN;
686}
687
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500688std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw3277faf2021-05-19 16:45:23 -0500689 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700690 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500691 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700692 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500693 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694}
695
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
697 nsecs_t currentTime = now();
698
Jeff Browndc5992e2014-04-11 01:27:26 -0700699 // Reset the key repeat timer whenever normal dispatch is suspended while the
700 // device is in a non-interactive state. This is to ensure that we abort a key
701 // repeat if the device is just coming out of sleep.
702 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 resetKeyRepeatLocked();
704 }
705
706 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
707 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100708 if (DEBUG_FOCUS) {
709 ALOGD("Dispatch frozen. Waiting some more.");
710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 return;
712 }
713
714 // Optimize latency of app switches.
715 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
716 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
717 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
718 if (mAppSwitchDueTime < *nextWakeupTime) {
719 *nextWakeupTime = mAppSwitchDueTime;
720 }
721
722 // Ready to start a new event.
723 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700725 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 if (isAppSwitchDue) {
727 // The inbound queue is empty so the app switch key we were waiting
728 // for will never arrive. Stop waiting for it.
729 resetPendingAppSwitchLocked(false);
730 isAppSwitchDue = false;
731 }
732
733 // Synthesize a key repeat if appropriate.
734 if (mKeyRepeatState.lastKeyEntry) {
735 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
736 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
737 } else {
738 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
739 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
740 }
741 }
742 }
743
744 // Nothing to do if there is no pending event.
745 if (!mPendingEvent) {
746 return;
747 }
748 } else {
749 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700750 mPendingEvent = mInboundQueue.front();
751 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 traceInboundQueueLengthLocked();
753 }
754
755 // Poke user activity for this event.
756 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700757 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 }
760
761 // Now we have an event to dispatch.
762 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700763 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700765 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700769 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 }
771
772 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700773 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 }
775
776 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700777 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700778 const ConfigurationChangedEntry& typedEntry =
779 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 break;
783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700785 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700786 const DeviceResetEntry& typedEntry =
787 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700788 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700790 break;
791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100793 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700794 std::shared_ptr<FocusEntry> typedEntry =
795 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100796 dispatchFocusLocked(currentTime, typedEntry);
797 done = true;
798 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
799 break;
800 }
801
Prabir Pradhan99987712020-11-10 18:43:05 -0800802 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
803 const auto typedEntry =
804 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
805 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
806 done = true;
807 break;
808 }
809
arthurhungb89ccb02020-12-30 16:19:01 +0800810 case EventEntry::Type::DRAG: {
811 std::shared_ptr<DragEntry> typedEntry =
812 std::static_pointer_cast<DragEntry>(mPendingEvent);
813 dispatchDragLocked(currentTime, typedEntry);
814 done = true;
815 break;
816 }
817
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700818 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700819 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700821 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 resetPendingAppSwitchLocked(true);
823 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700824 } else if (dropReason == DropReason::NOT_DROPPED) {
825 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 }
827 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700828 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700829 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700831 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
832 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700834 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 break;
836 }
837
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700838 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 std::shared_ptr<MotionEntry> motionEntry =
840 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700841 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
842 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700844 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700845 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700847 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
848 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 }
Chris Yef59a2f42020-10-16 12:55:26 -0700853
854 case EventEntry::Type::SENSOR: {
855 std::shared_ptr<SensorEntry> sensorEntry =
856 std::static_pointer_cast<SensorEntry>(mPendingEvent);
857 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
858 dropReason = DropReason::APP_SWITCH;
859 }
860 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
861 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
862 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
863 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
864 dropReason = DropReason::STALE;
865 }
866 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
867 done = true;
868 break;
869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
871
872 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700874 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
Michael Wright3a981722015-06-10 15:26:13 +0100876 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877
878 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 }
881}
882
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700883/**
884 * Return true if the events preceding this incoming motion event should be dropped
885 * Return false otherwise (the default behaviour)
886 */
887bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700888 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700889 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890
891 // Optimize case where the current application is unresponsive and the user
892 // decides to touch a window in a different application.
893 // If the application takes too long to catch up then we drop all events preceding
894 // the touch into the other window.
895 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700896 int32_t displayId = motionEntry.displayId;
897 int32_t x = static_cast<int32_t>(
898 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
899 int32_t y = static_cast<int32_t>(
900 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw3277faf2021-05-19 16:45:23 -0500901 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700902 findTouchedWindowAtLocked(displayId, x, y, nullptr);
903 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700904 touchedWindowHandle->getApplicationToken() !=
905 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700906 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907 ALOGI("Pruning input queue because user touched a different application while waiting "
908 "for %s",
909 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700910 return true;
911 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912
913 // Alternatively, maybe there's a gesture monitor that could handle this event
914 std::vector<TouchedMonitor> gestureMonitors =
915 findTouchedGestureMonitorsLocked(displayId, {});
916 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
917 sp<Connection> connection =
918 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000919 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700920 // This monitor could take more input. Drop all events preceding this
921 // event, so that gesture monitor could get a chance to receive the stream
922 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
923 "responsive gesture monitor that may handle the event",
924 mAwaitedFocusedApplication->getName().c_str());
925 return true;
926 }
927 }
928 }
929
930 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
931 // yet been processed by some connections, the dispatcher will wait for these motion
932 // events to be processed before dispatching the key event. This is because these motion events
933 // may cause a new window to be launched, which the user might expect to receive focus.
934 // To prevent waiting forever for such events, just send the key to the currently focused window
935 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
936 ALOGD("Received a new pointer down event, stop waiting for events to process and "
937 "just send the pending key event to the focused window.");
938 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700939 }
940 return false;
941}
942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700943bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700944 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700945 mInboundQueue.push_back(std::move(newEntry));
946 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 traceInboundQueueLengthLocked();
948
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700949 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700950 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 // Optimize app switch latency.
952 // If the application takes too long to catch up then we drop all events preceding
953 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700954 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700956 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700957 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700958 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700961 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700963 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 mAppSwitchSawKeyDown = false;
965 needWake = true;
966 }
967 }
968 }
969 break;
970 }
971
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700972 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700973 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
974 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700975 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100979 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700980 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
981 break;
982 }
983 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800984 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700985 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800986 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
987 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700988 // nothing to do
989 break;
990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 }
992
993 return needWake;
994}
995
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700996void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700997 // Do not store sensor event in recent queue to avoid flooding the queue.
998 if (entry->type != EventEntry::Type::SENSOR) {
999 mRecentQueue.push_back(entry);
1000 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001001 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001002 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
1004}
1005
chaviw3277faf2021-05-19 16:45:23 -05001006sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1007 int32_t y, TouchState* touchState,
1008 bool addOutsideTargets,
1009 bool addPortalWindows,
1010 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001011 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
1012 LOG_ALWAYS_FATAL(
1013 "Must provide a valid touch state if adding portal windows or outside targets");
1014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 // Traverse windows from front to back to find touched window.
chaviw3277faf2021-05-19 16:45:23 -05001016 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1017 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001018 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001019 continue;
1020 }
chaviw3277faf2021-05-19 16:45:23 -05001021 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001023 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
1025 if (windowInfo->visible) {
chaviw3277faf2021-05-19 16:45:23 -05001026 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1027 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1028 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001030 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1032 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001033 if (addPortalWindows) {
1034 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001035 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001036 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001037 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 // Found window.
1041 return windowHandle;
1042 }
1043 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001044
chaviw3277faf2021-05-19 16:45:23 -05001045 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001046 touchState->addOrUpdateWindow(windowHandle,
1047 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1048 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001053 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054}
1055
Garfield Tane84e6f92019-08-29 17:28:41 -07001056std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
chaviw3277faf2021-05-19 16:45:23 -05001057 int32_t displayId, const std::vector<sp<WindowInfoHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001058 std::vector<TouchedMonitor> touchedMonitors;
1059
1060 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1061 addGestureMonitors(monitors, touchedMonitors);
chaviw3277faf2021-05-19 16:45:23 -05001062 for (const sp<WindowInfoHandle>& portalWindow : portalWindows) {
1063 const WindowInfo* windowInfo = portalWindow->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001064 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1066 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001067 }
1068 return touchedMonitors;
1069}
1070
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001071void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 const char* reason;
1073 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 reason = "inbound event was dropped because the policy consumed it";
1079 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001080 case DropReason::DISABLED:
1081 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 ALOGI("Dropped event because input dispatch is disabled.");
1083 }
1084 reason = "inbound event was dropped because input dispatch is disabled";
1085 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 ALOGI("Dropped event because of pending overdue app switch.");
1088 reason = "inbound event was dropped because of pending overdue app switch";
1089 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001090 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 ALOGI("Dropped event because the current application is not responding and the user "
1092 "has started interacting with a different application.");
1093 reason = "inbound event was dropped because the current application is not responding "
1094 "and the user has started interacting with a different application";
1095 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001096 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 ALOGI("Dropped event because it is stale.");
1098 reason = "inbound event was dropped because it is stale";
1099 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001100 case DropReason::NO_POINTER_CAPTURE:
1101 ALOGI("Dropped event because there is no window with Pointer Capture.");
1102 reason = "inbound event was dropped because there is no window with Pointer Capture";
1103 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001104 case DropReason::NOT_DROPPED: {
1105 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 }
1109
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001110 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001111 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1113 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001116 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001117 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1118 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1120 synthesizeCancelationEventsForAllConnectionsLocked(options);
1121 } else {
1122 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1123 synthesizeCancelationEventsForAllConnectionsLocked(options);
1124 }
1125 break;
1126 }
Chris Yef59a2f42020-10-16 12:55:26 -07001127 case EventEntry::Type::SENSOR: {
1128 break;
1129 }
arthurhungb89ccb02020-12-30 16:19:01 +08001130 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1131 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001132 break;
1133 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001134 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001135 case EventEntry::Type::CONFIGURATION_CHANGED:
1136 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001137 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001138 break;
1139 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
1141}
1142
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001143static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1145 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146}
1147
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001148bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1149 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1150 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1151 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152}
1153
1154bool InputDispatcher::isAppSwitchPendingLocked() {
1155 return mAppSwitchDueTime != LONG_LONG_MAX;
1156}
1157
1158void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1159 mAppSwitchDueTime = LONG_LONG_MAX;
1160
1161#if DEBUG_APP_SWITCH
1162 if (handled) {
1163 ALOGD("App switch has arrived.");
1164 } else {
1165 ALOGD("App switch was abandoned.");
1166 }
1167#endif
1168}
1169
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001171 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172}
1173
1174bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001175 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 return false;
1177 }
1178
1179 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001180 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001181 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001183 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184
1185 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001186 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 return true;
1188}
1189
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001190void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1191 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192}
1193
1194void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001195 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001197 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 releaseInboundEventLocked(entry);
1199 }
1200 traceInboundQueueLengthLocked();
1201}
1202
1203void InputDispatcher::releasePendingEventLocked() {
1204 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001206 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
1208}
1209
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001210void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001212 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213#if DEBUG_DISPATCH_CYCLE
1214 ALOGD("Injected inbound event was dropped.");
1215#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001216 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
1218 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001219 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 }
1221 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222}
1223
1224void InputDispatcher::resetKeyRepeatLocked() {
1225 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001226 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 }
1228}
1229
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001230std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1231 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232
Michael Wright2e732952014-09-24 13:26:59 -07001233 uint32_t policyFlags = entry->policyFlags &
1234 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236 std::shared_ptr<KeyEntry> newEntry =
1237 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1238 entry->source, entry->displayId, policyFlags, entry->action,
1239 entry->flags, entry->keyCode, entry->scanCode,
1240 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242 newEntry->syntheticRepeat = true;
1243 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246}
1247
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001248bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252#endif
1253
1254 // Reset key repeating in case a keyboard device was added or removed or something.
1255 resetKeyRepeatLocked();
1256
1257 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001258 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1259 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001261 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 return true;
1263}
1264
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1266 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1269 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270#endif
1271
liushenxiang42232912021-05-21 20:24:09 +08001272 // Reset key repeating in case a keyboard device was disabled or enabled.
1273 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1274 resetKeyRepeatLocked();
1275 }
1276
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001277 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 synthesizeCancelationEventsForAllConnectionsLocked(options);
1280 return true;
1281}
1282
Vishnu Nairad321cd2020-08-20 16:40:21 -07001283void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001284 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001285 if (mPendingEvent != nullptr) {
1286 // Move the pending event to the front of the queue. This will give the chance
1287 // for the pending event to get dispatched to the newly focused window
1288 mInboundQueue.push_front(mPendingEvent);
1289 mPendingEvent = nullptr;
1290 }
1291
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 std::unique_ptr<FocusEntry> focusEntry =
1293 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1294 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001295
1296 // This event should go to the front of the queue, but behind all other focus events
1297 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001298 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001299 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 [](const std::shared_ptr<EventEntry>& event) {
1301 return event->type == EventEntry::Type::FOCUS;
1302 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001303
1304 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001306}
1307
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001308void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001309 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001310 if (channel == nullptr) {
1311 return; // Window has gone away
1312 }
1313 InputTarget target;
1314 target.inputChannel = channel;
1315 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1316 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001317 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1318 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001319 std::string reason = std::string("reason=").append(entry->reason);
1320 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001321 dispatchEventLocked(currentTime, entry, {target});
1322}
1323
Prabir Pradhan99987712020-11-10 18:43:05 -08001324void InputDispatcher::dispatchPointerCaptureChangedLocked(
1325 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1326 DropReason& dropReason) {
1327 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001328 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1329 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1330 }
1331 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 // Pointer capture was already forcefully disabled because of focus change.
1333 dropReason = DropReason::NOT_DROPPED;
1334 return;
1335 }
1336
1337 // Set drop reason for early returns
1338 dropReason = DropReason::NO_POINTER_CAPTURE;
1339
1340 sp<IBinder> token;
1341 if (entry->pointerCaptureEnabled) {
1342 // Enable Pointer Capture
1343 if (!mFocusedWindowRequestedPointerCapture) {
1344 // This can happen if a window requests capture and immediately releases capture.
1345 ALOGW("No window requested Pointer Capture.");
1346 return;
1347 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001348 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001349 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1350 mWindowTokenWithPointerCapture = token;
1351 } else {
1352 // Disable Pointer Capture
1353 token = mWindowTokenWithPointerCapture;
1354 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001355 if (mFocusedWindowRequestedPointerCapture) {
1356 mFocusedWindowRequestedPointerCapture = false;
1357 setPointerCaptureLocked(false);
1358 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001359 }
1360
1361 auto channel = getInputChannelLocked(token);
1362 if (channel == nullptr) {
1363 // Window has gone away, clean up Pointer Capture state.
1364 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001365 if (mFocusedWindowRequestedPointerCapture) {
1366 mFocusedWindowRequestedPointerCapture = false;
1367 setPointerCaptureLocked(false);
1368 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001369 return;
1370 }
1371 InputTarget target;
1372 target.inputChannel = channel;
1373 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1374 entry->dispatchInProgress = true;
1375 dispatchEventLocked(currentTime, entry, {target});
1376
1377 dropReason = DropReason::NOT_DROPPED;
1378}
1379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 if (!entry->dispatchInProgress) {
1384 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1385 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1386 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1387 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001388 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 // We have seen two identical key downs in a row which indicates that the device
1390 // driver is automatically generating key repeats itself. We take note of the
1391 // repeat here, but we disable our own next key repeat timer since it is clear that
1392 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001393 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1394 // Make sure we don't get key down from a different device. If a different
1395 // device Id has same key pressed down, the new device Id will replace the
1396 // current one to hold the key repeat with repeat count reset.
1397 // In the future when got a KEY_UP on the device id, drop it and do not
1398 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1400 resetKeyRepeatLocked();
1401 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1402 } else {
1403 // Not a repeat. Save key down state in case we do see a repeat later.
1404 resetKeyRepeatLocked();
1405 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1406 }
1407 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001408 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1409 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001410 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001411#if DEBUG_INBOUND_EVENT_DETAILS
1412 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1413#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 resetKeyRepeatLocked();
1416 }
1417
1418 if (entry->repeatCount == 1) {
1419 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1420 } else {
1421 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1422 }
1423
1424 entry->dispatchInProgress = true;
1425
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001426 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428
1429 // Handle case where the policy asked us to try again later last time.
1430 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1431 if (currentTime < entry->interceptKeyWakeupTime) {
1432 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1433 *nextWakeupTime = entry->interceptKeyWakeupTime;
1434 }
1435 return false; // wait until next wakeup
1436 }
1437 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1438 entry->interceptKeyWakeupTime = 0;
1439 }
1440
1441 // Give the policy a chance to intercept the key.
1442 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1443 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001444 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001445 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001446 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001447 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001448 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001450 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return false; // wait for the command to run
1452 } else {
1453 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1454 }
1455 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001456 if (*dropReason == DropReason::NOT_DROPPED) {
1457 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 }
1459 }
1460
1461 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001462 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001463 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001464 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1465 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001466 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 return true;
1468 }
1469
1470 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001471 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001472 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001473 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return false;
1476 }
1477
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001478 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001479 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 return true;
1481 }
1482
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001483 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001484 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485
1486 // Dispatch the key.
1487 dispatchEventLocked(currentTime, entry, inputTargets);
1488 return true;
1489}
1490
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001491void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001493 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1495 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001496 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1497 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1498 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499#endif
1500}
1501
Chris Yef59a2f42020-10-16 12:55:26 -07001502void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1503 mLock.unlock();
1504
1505 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1506 if (entry->accuracyChanged) {
1507 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1508 }
1509 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1510 entry->hwTimestamp, entry->values);
1511 mLock.lock();
1512}
1513
1514void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1515 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1516#if DEBUG_OUTBOUND_EVENT_DETAILS
1517 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1518 "source=0x%x, sensorType=%s",
1519 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001520 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001521#endif
1522 std::unique_ptr<CommandEntry> commandEntry =
1523 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1524 commandEntry->sensorEntry = entry;
1525 postCommandLocked(std::move(commandEntry));
1526}
1527
1528bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1529#if DEBUG_OUTBOUND_EVENT_DETAILS
1530 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1531 NamedEnum::string(sensorType).c_str());
1532#endif
1533 { // acquire lock
1534 std::scoped_lock _l(mLock);
1535
1536 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1537 std::shared_ptr<EventEntry> entry = *it;
1538 if (entry->type == EventEntry::Type::SENSOR) {
1539 it = mInboundQueue.erase(it);
1540 releaseInboundEventLocked(entry);
1541 }
1542 }
1543 }
1544 return true;
1545}
1546
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001547bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001549 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001551 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 entry->dispatchInProgress = true;
1553
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001554 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 }
1556
1557 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001558 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001559 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1561 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 return true;
1563 }
1564
1565 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1566
1567 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001568 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569
1570 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 if (isPointerEvent) {
1573 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001574 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 } else {
1578 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001580 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 return false;
1584 }
1585
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001586 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001587 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001588 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1589 return true;
1590 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001591 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001592 CancelationOptions::Mode mode(isPointerEvent
1593 ? CancelationOptions::CANCEL_POINTER_EVENTS
1594 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1595 CancelationOptions options(mode, "input event injection failed");
1596 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 return true;
1598 }
1599
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001600 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001601 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001603 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001604 std::unordered_map<int32_t, TouchState>::iterator it =
1605 mTouchStatesByDisplay.find(entry->displayId);
1606 if (it != mTouchStatesByDisplay.end()) {
1607 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001608 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001609 // The event has gone through these portal windows, so we add monitoring targets of
1610 // the corresponding displays as well.
1611 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05001612 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001613 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001615 }
1616 }
1617 }
1618 }
1619
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 // Dispatch the motion.
1621 if (conflictingPointerActions) {
1622 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001623 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 synthesizeCancelationEventsForAllConnectionsLocked(options);
1625 }
1626 dispatchEventLocked(currentTime, entry, inputTargets);
1627 return true;
1628}
1629
chaviw3277faf2021-05-19 16:45:23 -05001630void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001631 bool isExiting, const MotionEntry& motionEntry) {
1632 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1633 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1634 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1635 PointerCoords pointerCoords;
1636 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1637 pointerCoords.transform(windowHandle->getInfo()->transform);
1638
1639 std::unique_ptr<DragEntry> dragEntry =
1640 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1641 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1642 pointerCoords.getY());
1643
1644 enqueueInboundEventLocked(std::move(dragEntry));
1645}
1646
1647void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1648 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1649 if (channel == nullptr) {
1650 return; // Window has gone away
1651 }
1652 InputTarget target;
1653 target.inputChannel = channel;
1654 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1655 entry->dispatchInProgress = true;
1656 dispatchEventLocked(currentTime, entry, {target});
1657}
1658
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001659void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001661 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 ", policyFlags=0x%x, "
1663 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1664 "metaState=0x%x, buttonState=0x%x,"
1665 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001666 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1667 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1668 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001672 "x=%f, y=%f, pressure=%f, size=%f, "
1673 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1674 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1676 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1677 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1678 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1679 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1680 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1681 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1682 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1683 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1684 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 }
1686#endif
1687}
1688
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001689void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1690 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001691 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001692 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693#if DEBUG_DISPATCH_CYCLE
1694 ALOGD("dispatchEventToCurrentInputTargets");
1695#endif
1696
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001697 updateInteractionTokensLocked(*eventEntry, inputTargets);
1698
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1700
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001703 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001704 sp<Connection> connection =
1705 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001706 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001707 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001709 if (DEBUG_FOCUS) {
1710 ALOGD("Dropping event delivery to target with channel '%s' because it "
1711 "is no longer registered with the input dispatcher.",
1712 inputTarget.inputChannel->getName().c_str());
1713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 }
1715 }
1716}
1717
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001718void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1719 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1720 // If the policy decides to close the app, we will get a channel removal event via
1721 // unregisterInputChannel, and will clean up the connection that way. We are already not
1722 // sending new pointers to the connection when it blocked, but focused events will continue to
1723 // pile up.
1724 ALOGW("Canceling events for %s because it is unresponsive",
1725 connection->inputChannel->getName().c_str());
1726 if (connection->status == Connection::STATUS_NORMAL) {
1727 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1728 "application not responding");
1729 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
1731}
1732
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001733void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001734 if (DEBUG_FOCUS) {
1735 ALOGD("Resetting ANR timeouts.");
1736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
1738 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001739 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001740 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741}
1742
Tiger Huang721e26f2018-07-24 22:26:19 +08001743/**
1744 * Get the display id that the given event should go to. If this event specifies a valid display id,
1745 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1746 * Focused display is the display that the user most recently interacted with.
1747 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001748int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001749 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001750 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001751 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001752 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1753 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 break;
1755 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001756 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1758 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001759 break;
1760 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001761 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001762 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001763 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001764 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001765 case EventEntry::Type::SENSOR:
1766 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001767 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001768 return ADISPLAY_ID_NONE;
1769 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001770 }
1771 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1772}
1773
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001774bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1775 const char* focusedWindowName) {
1776 if (mAnrTracker.empty()) {
1777 // already processed all events that we waited for
1778 mKeyIsWaitingForEventsTimeout = std::nullopt;
1779 return false;
1780 }
1781
1782 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1783 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001784 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001785 mKeyIsWaitingForEventsTimeout = currentTime +
1786 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1787 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001788 return true;
1789 }
1790
1791 // We still have pending events, and already started the timer
1792 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1793 return true; // Still waiting
1794 }
1795
1796 // Waited too long, and some connection still hasn't processed all motions
1797 // Just send the key to the focused window
1798 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1799 focusedWindowName);
1800 mKeyIsWaitingForEventsTimeout = std::nullopt;
1801 return false;
1802}
1803
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1805 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1806 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001807 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808
Tiger Huang721e26f2018-07-24 22:26:19 +08001809 int32_t displayId = getTargetDisplayId(entry);
chaviw3277faf2021-05-19 16:45:23 -05001810 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001811 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001812 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1813
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 // If there is no currently focused window and no focused application
1815 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001816 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1817 ALOGI("Dropping %s event because there is no focused window or focused application in "
1818 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001819 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001820 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1824 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1825 // start interacting with another application via touch (app switch). This code can be removed
1826 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1827 // an app is expected to have a focused window.
1828 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1829 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1830 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001831 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1832 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1833 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001834 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001835 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 ALOGW("Waiting because no window has focus but %s may eventually add a "
1837 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001838 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1842 // Already raised ANR. Drop the event
1843 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001844 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001846 } else {
1847 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 }
1850 }
1851
1852 // we have a valid, non-null focused window
1853 resetNoFocusedWindowTimeoutLocked();
1854
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001856 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 }
1859
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001860 if (focusedWindowHandle->getInfo()->paused) {
1861 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001863 }
1864
1865 // If the event is a key event, then we must wait for all previous events to
1866 // complete before delivering it because previous events may have the
1867 // side-effect of transferring focus to a different window and we want to
1868 // ensure that the following keys are sent to the new window.
1869 //
1870 // Suppose the user touches a button in a window then immediately presses "A".
1871 // If the button causes a pop-up window to appear then we want to ensure that
1872 // the "A" key is delivered to the new pop-up window. This is because users
1873 // often anticipate pending UI changes when typing on a keyboard.
1874 // To obtain this behavior, we must serialize key events with respect to all
1875 // prior input events.
1876 if (entry.type == EventEntry::Type::KEY) {
1877 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1878 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
1882
1883 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001884 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001885 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1886 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887
1888 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001889 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890}
1891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892/**
1893 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1894 * that are currently unresponsive.
1895 */
1896std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1897 const std::vector<TouchedMonitor>& monitors) const {
1898 std::vector<TouchedMonitor> responsiveMonitors;
1899 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1900 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1901 sp<Connection> connection = getConnectionLocked(
1902 monitor.monitor.inputChannel->getConnectionToken());
1903 if (connection == nullptr) {
1904 ALOGE("Could not find connection for monitor %s",
1905 monitor.monitor.inputChannel->getName().c_str());
1906 return false;
1907 }
1908 if (!connection->responsive) {
1909 ALOGW("Unresponsive monitor %s will not get the new gesture",
1910 connection->inputChannel->getName().c_str());
1911 return false;
1912 }
1913 return true;
1914 });
1915 return responsiveMonitors;
1916}
1917
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001918InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1919 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1920 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001921 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 enum InjectionPermission {
1923 INJECTION_PERMISSION_UNKNOWN,
1924 INJECTION_PERMISSION_GRANTED,
1925 INJECTION_PERMISSION_DENIED
1926 };
1927
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 // For security reasons, we defer updating the touch state until we are sure that
1929 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001930 int32_t displayId = entry.displayId;
1931 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1933
1934 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw3277faf2021-05-19 16:45:23 -05001937 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1938 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001940 // Copy current touch state into tempTouchState.
1941 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1942 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001943 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001945 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1946 mTouchStatesByDisplay.find(displayId);
1947 if (oldStateIt != mTouchStatesByDisplay.end()) {
1948 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001949 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001950 }
1951
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 bool isSplit = tempTouchState.split;
1953 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1954 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1955 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001956 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1957 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1958 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1959 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1960 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001961 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 bool wrongDevice = false;
1963 if (newGesture) {
1964 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001965 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001966 ALOGI("Dropping event because a pointer for a different device is already down "
1967 "in display %" PRId32,
1968 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001969 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 switchedDevice = false;
1972 wrongDevice = true;
1973 goto Failed;
1974 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001975 tempTouchState.reset();
1976 tempTouchState.down = down;
1977 tempTouchState.deviceId = entry.deviceId;
1978 tempTouchState.source = entry.source;
1979 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001981 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001982 ALOGI("Dropping move event because a pointer for a different device is already active "
1983 "in display %" PRId32,
1984 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001985 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001987 switchedDevice = false;
1988 wrongDevice = true;
1989 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 }
1991
1992 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1993 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1994
Garfield Tan00f511d2019-06-12 16:55:40 -07001995 int32_t x;
1996 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001998 // Always dispatch mouse events to cursor position.
1999 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002000 x = int32_t(entry.xCursorPosition);
2001 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002002 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002003 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2004 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002005 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002006 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07002007 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002008 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2009 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002010
2011 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002012 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002013 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002016 if (newTouchedWindowHandle != nullptr &&
2017 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002018 // New window supports splitting, but we should never split mouse events.
2019 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 } else if (isSplit) {
2021 // New window does not support splitting but we have already split events.
2022 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002023 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 }
2025
2026 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002027 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002029 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002030 }
2031
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002032 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2033 ALOGI("Not sending touch event to %s because it is paused",
2034 newTouchedWindowHandle->getName().c_str());
2035 newTouchedWindowHandle = nullptr;
2036 }
2037
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002038 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002039 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002040 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2041 if (!isResponsive) {
2042 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002043 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2044 newTouchedWindowHandle = nullptr;
2045 }
2046 }
2047
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002048 // Drop events that can't be trusted due to occlusion
2049 if (newTouchedWindowHandle != nullptr &&
2050 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2051 TouchOcclusionInfo occlusionInfo =
2052 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002053 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002054 if (DEBUG_TOUCH_OCCLUSION) {
2055 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2056 for (const auto& log : occlusionInfo.debugInfo) {
2057 ALOGD("%s", log.c_str());
2058 }
2059 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002060 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2061 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2062 ALOGW("Dropping untrusted touch event due to %s/%d",
2063 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2064 newTouchedWindowHandle = nullptr;
2065 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002066 }
2067 }
2068
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 // Also don't send the new touch event to unresponsive gesture monitors
2070 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2071
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2073 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074 "(%d, %d) in display %" PRId32 ".",
2075 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 goto Failed;
2078 }
2079
2080 if (newTouchedWindowHandle != nullptr) {
2081 // Set target flags.
2082 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2083 if (isSplit) {
2084 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002086 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2087 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2088 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2089 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2090 }
2091
2092 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002093 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2094 newHoverWindowHandle = nullptr;
2095 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002096 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002097 }
2098
2099 // Update the temporary touch state.
2100 BitSet32 pointerIds;
2101 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002102 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002103 pointerIds.markBit(pointerId);
2104 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002105 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
2107
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002108 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 } else {
2110 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2111
2112 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002113 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002114 if (DEBUG_FOCUS) {
2115 ALOGD("Dropping event because the pointer is not down or we previously "
2116 "dropped the pointer down event in display %" PRId32,
2117 displayId);
2118 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002119 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 goto Failed;
2121 }
2122
arthurhung6d4bed92021-03-17 11:59:33 +08002123 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002124
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002126 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002128 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2129 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130
chaviw3277faf2021-05-19 16:45:23 -05002131 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002132 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002133 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002134 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2135 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002136 if (DEBUG_FOCUS) {
2137 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2138 oldTouchedWindowHandle->getName().c_str(),
2139 newTouchedWindowHandle->getName().c_str(), displayId);
2140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002142 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2143 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2144 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145
2146 // Make a slippery entrance into the new window.
2147 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2148 isSplit = true;
2149 }
2150
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002151 int32_t targetFlags =
2152 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 if (isSplit) {
2154 targetFlags |= InputTarget::FLAG_SPLIT;
2155 }
2156 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2157 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002158 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2159 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161
2162 BitSet32 pointerIds;
2163 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002164 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002166 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 }
2168 }
2169 }
2170
2171 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002172 // Let the previous window know that the hover sequence is over, unless we already did it
2173 // when dispatching it as is to newTouchedWindowHandle.
2174 if (mLastHoverWindowHandle != nullptr &&
2175 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2176 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177#if DEBUG_HOVER
2178 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002181 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2182 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
2184
Garfield Tandf26e862020-07-01 20:18:19 -07002185 // Let the new window know that the hover sequence is starting, unless we already did it
2186 // when dispatching it as is to newTouchedWindowHandle.
2187 if (newHoverWindowHandle != nullptr &&
2188 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2189 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190#if DEBUG_HOVER
2191 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002192 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2195 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2196 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198 }
2199
2200 // Check permission to inject into all touched foreground windows and ensure there
2201 // is at least one touched foreground window.
2202 {
2203 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2206 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002207 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002208 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 injectionPermission = INJECTION_PERMISSION_DENIED;
2210 goto Failed;
2211 }
2212 }
2213 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002214 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002215 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002216 ALOGI("Dropping event because there is no touched foreground window in display "
2217 "%" PRId32 " or gesture monitor to receive it.",
2218 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002219 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 goto Failed;
2221 }
2222
2223 // Permission granted to injection into all touched foreground windows.
2224 injectionPermission = INJECTION_PERMISSION_GRANTED;
2225 }
2226
2227 // Check whether windows listening for outside touches are owned by the same UID. If it is
2228 // set the policy flag that we will not reveal coordinate information to this window.
2229 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002230 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002231 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002232 if (foregroundWindowHandle) {
2233 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002234 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002235 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw3277faf2021-05-19 16:45:23 -05002236 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2237 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2238 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002239 InputTarget::FLAG_ZERO_COORDS,
2240 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 }
2243 }
2244 }
2245 }
2246
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // If this is the first pointer going down and the touched window has a wallpaper
2248 // then also add the touched wallpaper windows so they are locked in for the duration
2249 // of the touch gesture.
2250 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2251 // engine only supports touch events. We would need to add a mechanism similar
2252 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2253 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002254 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002255 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002256 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw3277faf2021-05-19 16:45:23 -05002257 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002258 getWindowHandlesLocked(displayId);
chaviw3277faf2021-05-19 16:45:23 -05002259 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2260 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002261 if (info->displayId == displayId &&
chaviw3277faf2021-05-19 16:45:23 -05002262 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002263 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 .addOrUpdateWindow(windowHandle,
2265 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2266 InputTarget::
2267 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2268 InputTarget::FLAG_DISPATCH_AS_IS,
2269 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271 }
2272 }
2273 }
2274
2275 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002276 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002283 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002286 }
2287
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 // Drop the outside or hover touch windows since we will not care about them
2289 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002290 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291
2292Failed:
2293 // Check injection permission once and for all.
2294 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002295 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 injectionPermission = INJECTION_PERMISSION_GRANTED;
2297 } else {
2298 injectionPermission = INJECTION_PERMISSION_DENIED;
2299 }
2300 }
2301
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002302 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2303 return injectionResult;
2304 }
2305
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002307 if (!wrongDevice) {
2308 if (switchedDevice) {
2309 if (DEBUG_FOCUS) {
2310 ALOGD("Conflicting pointer actions: Switched to a different device.");
2311 }
2312 *outConflictingPointerActions = true;
2313 }
2314
2315 if (isHoverAction) {
2316 // Started hovering, therefore no longer down.
2317 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002318 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002319 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2320 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 *outConflictingPointerActions = true;
2323 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002324 tempTouchState.reset();
2325 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2326 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2327 tempTouchState.deviceId = entry.deviceId;
2328 tempTouchState.source = entry.source;
2329 tempTouchState.displayId = displayId;
2330 }
2331 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2332 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2333 // All pointers up or canceled.
2334 tempTouchState.reset();
2335 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2336 // First pointer went down.
2337 if (oldState && oldState->down) {
2338 if (DEBUG_FOCUS) {
2339 ALOGD("Conflicting pointer actions: Down received while already down.");
2340 }
2341 *outConflictingPointerActions = true;
2342 }
2343 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2344 // One pointer went up.
2345 if (isSplit) {
2346 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2347 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002349 for (size_t i = 0; i < tempTouchState.windows.size();) {
2350 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2351 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2352 touchedWindow.pointerIds.clearBit(pointerId);
2353 if (touchedWindow.pointerIds.isEmpty()) {
2354 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2355 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002360 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002361 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002362
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002363 // Save changes unless the action was scroll in which case the temporary touch
2364 // state was only valid for this one action.
2365 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2366 if (tempTouchState.displayId >= 0) {
2367 mTouchStatesByDisplay[displayId] = tempTouchState;
2368 } else {
2369 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002373 // Update hover state.
2374 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
2376
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 return injectionResult;
2378}
2379
arthurhung6d4bed92021-03-17 11:59:33 +08002380void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw3277faf2021-05-19 16:45:23 -05002381 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002382 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2383 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2384 true /*ignoreDragWindow*/);
2385 if (dropWindow) {
2386 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2387 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002388 } else {
2389 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002390 }
2391 mDragState.reset();
2392}
2393
2394void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2395 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002396 return;
2397 }
2398
arthurhung6d4bed92021-03-17 11:59:33 +08002399 if (!mDragState->isStartDrag) {
2400 mDragState->isStartDrag = true;
2401 mDragState->isStylusButtonDownAtStart =
2402 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2403 }
2404
arthurhungb89ccb02020-12-30 16:19:01 +08002405 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2406 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2407 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2408 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002409 // Handle the special case : stylus button no longer pressed.
2410 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2411 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2412 finishDragAndDrop(entry.displayId, x, y);
2413 return;
2414 }
2415
chaviw3277faf2021-05-19 16:45:23 -05002416 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002417 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002418 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2419 true /*ignoreDragWindow*/);
2420 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002421 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2422 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2423 if (mDragState->dragHoverWindowHandle != nullptr) {
2424 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2425 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002426 }
arthurhung6d4bed92021-03-17 11:59:33 +08002427 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002428 }
2429 // enqueue drag location if needed.
2430 if (hoverWindowHandle != nullptr) {
2431 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2432 }
arthurhung6d4bed92021-03-17 11:59:33 +08002433 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2434 finishDragAndDrop(entry.displayId, x, y);
2435 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002436 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002437 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002438 }
2439}
2440
chaviw3277faf2021-05-19 16:45:23 -05002441void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002442 int32_t targetFlags, BitSet32 pointerIds,
2443 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002444 std::vector<InputTarget>::iterator it =
2445 std::find_if(inputTargets.begin(), inputTargets.end(),
2446 [&windowHandle](const InputTarget& inputTarget) {
2447 return inputTarget.inputChannel->getConnectionToken() ==
2448 windowHandle->getToken();
2449 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002450
chaviw3277faf2021-05-19 16:45:23 -05002451 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002452
2453 if (it == inputTargets.end()) {
2454 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002455 std::shared_ptr<InputChannel> inputChannel =
2456 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002457 if (inputChannel == nullptr) {
2458 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2459 return;
2460 }
2461 inputTarget.inputChannel = inputChannel;
2462 inputTarget.flags = targetFlags;
2463 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002464 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002465 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002466 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002467 inputTargets.push_back(inputTarget);
2468 it = inputTargets.end() - 1;
2469 }
2470
2471 ALOG_ASSERT(it->flags == targetFlags);
2472 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2473
chaviw1ff3d1e2020-07-01 15:53:47 -07002474 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475}
2476
Michael Wright3dd60e22019-03-27 22:06:44 +00002477void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002478 int32_t displayId, float xOffset,
2479 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002480 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2481 mGlobalMonitorsByDisplay.find(displayId);
2482
2483 if (it != mGlobalMonitorsByDisplay.end()) {
2484 const std::vector<Monitor>& monitors = it->second;
2485 for (const Monitor& monitor : monitors) {
2486 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
2489}
2490
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2492 float yOffset,
2493 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002494 InputTarget target;
2495 target.inputChannel = monitor.inputChannel;
2496 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002497 ui::Transform t;
2498 t.set(xOffset, yOffset);
2499 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002500 inputTargets.push_back(target);
2501}
2502
chaviw3277faf2021-05-19 16:45:23 -05002503bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 const InjectionState* injectionState) {
2505 if (injectionState &&
2506 (windowHandle == nullptr ||
2507 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2508 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002509 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 "owned by uid %d",
2512 injectionState->injectorPid, injectionState->injectorUid,
2513 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 } else {
2515 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 }
2518 return false;
2519 }
2520 return true;
2521}
2522
Robert Carrc9bf1d32020-04-13 17:21:08 -07002523/**
2524 * Indicate whether one window handle should be considered as obscuring
2525 * another window handle. We only check a few preconditions. Actually
2526 * checking the bounds is left to the caller.
2527 */
chaviw3277faf2021-05-19 16:45:23 -05002528static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2529 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002530 // Compare by token so cloned layers aren't counted
2531 if (haveSameToken(windowHandle, otherHandle)) {
2532 return false;
2533 }
2534 auto info = windowHandle->getInfo();
2535 auto otherInfo = otherHandle->getInfo();
2536 if (!otherInfo->visible) {
2537 return false;
chaviw3277faf2021-05-19 16:45:23 -05002538 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002539 // Those act as if they were invisible, so we don't need to flag them.
2540 // We do want to potentially flag touchable windows even if they have 0
2541 // opacity, since they can consume touches and alter the effects of the
2542 // user interaction (eg. apps that rely on
2543 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2544 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2545 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002546 } else if (info->ownerUid == otherInfo->ownerUid) {
2547 // If ownerUid is the same we don't generate occlusion events as there
2548 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002549 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002550 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002551 return false;
2552 } else if (otherInfo->displayId != info->displayId) {
2553 return false;
2554 }
2555 return true;
2556}
2557
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002558/**
2559 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2560 * untrusted, one should check:
2561 *
2562 * 1. If result.hasBlockingOcclusion is true.
2563 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2564 * BLOCK_UNTRUSTED.
2565 *
2566 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2567 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2568 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2569 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2570 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2571 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2572 *
2573 * If neither of those is true, then it means the touch can be allowed.
2574 */
2575InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw3277faf2021-05-19 16:45:23 -05002576 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2577 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002578 int32_t displayId = windowInfo->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002579 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002580 TouchOcclusionInfo info;
2581 info.hasBlockingOcclusion = false;
2582 info.obscuringOpacity = 0;
2583 info.obscuringUid = -1;
2584 std::map<int32_t, float> opacityByUid;
chaviw3277faf2021-05-19 16:45:23 -05002585 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002586 if (windowHandle == otherHandle) {
2587 break; // All future windows are below us. Exit early.
2588 }
chaviw3277faf2021-05-19 16:45:23 -05002589 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002590 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2591 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002592 if (DEBUG_TOUCH_OCCLUSION) {
2593 info.debugInfo.push_back(
2594 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2595 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002596 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2597 // we perform the checks below to see if the touch can be propagated or not based on the
2598 // window's touch occlusion mode
2599 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2600 info.hasBlockingOcclusion = true;
2601 info.obscuringUid = otherInfo->ownerUid;
2602 info.obscuringPackage = otherInfo->packageName;
2603 break;
2604 }
2605 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2606 uint32_t uid = otherInfo->ownerUid;
2607 float opacity =
2608 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2609 // Given windows A and B:
2610 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2611 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2612 opacityByUid[uid] = opacity;
2613 if (opacity > info.obscuringOpacity) {
2614 info.obscuringOpacity = opacity;
2615 info.obscuringUid = uid;
2616 info.obscuringPackage = otherInfo->packageName;
2617 }
2618 }
2619 }
2620 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002621 if (DEBUG_TOUCH_OCCLUSION) {
2622 info.debugInfo.push_back(
2623 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2624 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002625 return info;
2626}
2627
chaviw3277faf2021-05-19 16:45:23 -05002628std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002629 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002630 return StringPrintf(INDENT2
2631 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2632 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2633 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2634 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002635 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002636 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002637 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002638 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2639 info->frameTop, info->frameRight, info->frameBottom,
2640 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002641 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2642 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2643 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002644}
2645
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002646bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2647 if (occlusionInfo.hasBlockingOcclusion) {
2648 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2649 occlusionInfo.obscuringUid);
2650 return false;
2651 }
2652 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2653 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2654 "%.2f, maximum allowed = %.2f)",
2655 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2656 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2657 return false;
2658 }
2659 return true;
2660}
2661
chaviw3277faf2021-05-19 16:45:23 -05002662bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002665 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2666 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002667 if (windowHandle == otherHandle) {
2668 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 }
chaviw3277faf2021-05-19 16:45:23 -05002670 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002671 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002672 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 return true;
2674 }
2675 }
2676 return false;
2677}
2678
chaviw3277faf2021-05-19 16:45:23 -05002679bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002680 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002681 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2682 const WindowInfo* windowInfo = windowHandle->getInfo();
2683 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002684 if (windowHandle == otherHandle) {
2685 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002686 }
chaviw3277faf2021-05-19 16:45:23 -05002687 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002688 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002689 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002690 return true;
2691 }
2692 }
2693 return false;
2694}
2695
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002696std::string InputDispatcher::getApplicationWindowLabel(
chaviw3277faf2021-05-19 16:45:23 -05002697 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002698 if (applicationHandle != nullptr) {
2699 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002700 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 } else {
2702 return applicationHandle->getName();
2703 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002704 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002705 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002707 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 }
2709}
2710
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002711void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002712 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002713 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2714 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002715 // Focus or pointer capture changed events are passed to apps, but do not represent user
2716 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002717 return;
2718 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002719 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw3277faf2021-05-19 16:45:23 -05002720 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002721 if (focusedWindowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05002722 const WindowInfo* info = focusedWindowHandle->getInfo();
2723 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002725 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726#endif
2727 return;
2728 }
2729 }
2730
2731 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002732 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002733 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002734 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2735 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 return;
2737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002739 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 eventType = USER_ACTIVITY_EVENT_TOUCH;
2741 }
2742 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002744 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002745 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2746 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 return;
2748 }
2749 eventType = USER_ACTIVITY_EVENT_BUTTON;
2750 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002752 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002753 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002754 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002755 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002756 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2757 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002758 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002759 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002760 break;
2761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
2763
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002764 std::unique_ptr<CommandEntry> commandEntry =
2765 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002766 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002768 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002769 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770}
2771
2772void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002774 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002775 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002776 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002778 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002779 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002780 ATRACE_NAME(message.c_str());
2781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782#if DEBUG_DISPATCH_CYCLE
2783 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002784 "globalScaleFactor=%f, pointerIds=0x%x %s",
2785 connection->getInputChannelName().c_str(), inputTarget.flags,
2786 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2787 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788#endif
2789
2790 // Skip this event if the connection status is not normal.
2791 // We don't want to enqueue additional outbound events if the connection is broken.
2792 if (connection->status != Connection::STATUS_NORMAL) {
2793#if DEBUG_DISPATCH_CYCLE
2794 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002795 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796#endif
2797 return;
2798 }
2799
2800 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002801 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2802 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2803 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002804 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002806 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002807 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002808 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002809 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 if (!splitMotionEntry) {
2811 return; // split event was dropped
2812 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002813 if (DEBUG_FOCUS) {
2814 ALOGD("channel '%s' ~ Split motion event.",
2815 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002816 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002817 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002818 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2819 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 return;
2821 }
2822 }
2823
2824 // Not splitting. Enqueue dispatch entries for the event as is.
2825 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2826}
2827
2828void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002830 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002831 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002832 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002834 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002835 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002836 ATRACE_NAME(message.c_str());
2837 }
2838
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002839 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840
2841 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002844 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002846 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002848 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002850 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002852 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002853 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854
2855 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002856 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 startDispatchCycleLocked(currentTime, connection);
2858 }
2859}
2860
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002862 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002863 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002864 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002865 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002866 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2867 connection->getInputChannelName().c_str(),
2868 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002869 ATRACE_NAME(message.c_str());
2870 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002871 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 if (!(inputTargetFlags & dispatchMode)) {
2873 return;
2874 }
2875 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2876
2877 // This is a new event.
2878 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002879 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002880 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002882 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2883 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002884 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002886 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002887 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002888 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002889 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002890 dispatchEntry->resolvedAction = keyEntry.action;
2891 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2894 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2897 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 return; // skip the inconsistent event
2900 }
2901 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002904 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002905 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002906 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2907 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2908 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2909 static_cast<int32_t>(IdGenerator::Source::OTHER);
2910 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2912 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2913 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2914 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2915 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2916 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2917 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2918 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2919 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2920 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2921 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002922 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002923 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 }
2925 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2927 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2930 "event",
2931 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002933 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2934 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002938 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2940 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2941 }
2942 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2943 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2947 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2950 "event",
2951 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002953 return; // skip the inconsistent event
2954 }
2955
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002956 dispatchEntry->resolvedEventId =
2957 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2958 ? mIdGenerator.nextId()
2959 : motionEntry.id;
2960 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2961 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2962 ") to MotionEvent(id=0x%" PRIx32 ").",
2963 motionEntry.id, dispatchEntry->resolvedEventId);
2964 ATRACE_NAME(message.c_str());
2965 }
2966
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002967 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2968 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2969 // Skip reporting pointer down outside focus to the policy.
2970 break;
2971 }
2972
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002973 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002974 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002975
2976 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002978 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002979 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2980 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002981 break;
2982 }
Chris Yef59a2f42020-10-16 12:55:26 -07002983 case EventEntry::Type::SENSOR: {
2984 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2985 break;
2986 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002987 case EventEntry::Type::CONFIGURATION_CHANGED:
2988 case EventEntry::Type::DEVICE_RESET: {
2989 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002990 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002991 break;
2992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 }
2994
2995 // Remember that we are waiting for this dispatch to complete.
2996 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002997 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002998 }
2999
3000 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003001 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003002 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003003}
3004
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003005/**
3006 * This function is purely for debugging. It helps us understand where the user interaction
3007 * was taking place. For example, if user is touching launcher, we will see a log that user
3008 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3009 * We will see both launcher and wallpaper in that list.
3010 * Once the interaction with a particular set of connections starts, no new logs will be printed
3011 * until the set of interacted connections changes.
3012 *
3013 * The following items are skipped, to reduce the logspam:
3014 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3015 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3016 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3017 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3018 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003019 */
3020void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3021 const std::vector<InputTarget>& targets) {
3022 // Skip ACTION_UP events, and all events other than keys and motions
3023 if (entry.type == EventEntry::Type::KEY) {
3024 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3025 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3026 return;
3027 }
3028 } else if (entry.type == EventEntry::Type::MOTION) {
3029 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3030 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3031 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3032 return;
3033 }
3034 } else {
3035 return; // Not a key or a motion
3036 }
3037
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003038 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003039 std::vector<sp<Connection>> newConnections;
3040 for (const InputTarget& target : targets) {
3041 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3042 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3043 continue; // Skip windows that receive ACTION_OUTSIDE
3044 }
3045
3046 sp<IBinder> token = target.inputChannel->getConnectionToken();
3047 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003048 if (connection == nullptr) {
3049 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003050 }
3051 newConnectionTokens.insert(std::move(token));
3052 newConnections.emplace_back(connection);
3053 }
3054 if (newConnectionTokens == mInteractionConnectionTokens) {
3055 return; // no change
3056 }
3057 mInteractionConnectionTokens = newConnectionTokens;
3058
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003059 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003060 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003061 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003062 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003063 std::string message = "Interaction with: " + targetList;
3064 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003065 message += "<none>";
3066 }
3067 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3068}
3069
chaviwfd6d3512019-03-25 13:23:49 -07003070void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003071 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003072 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003073 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3074 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003075 return;
3076 }
3077
Vishnu Nairc519ff72021-01-21 08:23:08 -08003078 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003079 if (focusedToken == token) {
3080 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003081 return;
3082 }
3083
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003084 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3085 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003086 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003087 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088}
3089
3090void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003092 if (ATRACE_ENABLED()) {
3093 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003095 ATRACE_NAME(message.c_str());
3096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099#endif
3100
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003101 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3102 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003104 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003105 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003106 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107
3108 // Publish the event.
3109 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003110 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3111 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003112 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003113 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3114 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003117 status = connection->inputPublisher
3118 .publishKeyEvent(dispatchEntry->seq,
3119 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3120 keyEntry.source, keyEntry.displayId,
3121 std::move(hmac), dispatchEntry->resolvedAction,
3122 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3123 keyEntry.scanCode, keyEntry.metaState,
3124 keyEntry.repeatCount, keyEntry.downTime,
3125 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 }
3128
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003129 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003130 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003133 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134
chaviw82357092020-01-28 13:13:06 -08003135 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003136 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3138 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003139 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003140 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3141 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003142 // Don't apply window scale here since we don't want scale to affect raw
3143 // coordinates. The scale will be sent back to the client and applied
3144 // later when requesting relative coordinates.
3145 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3146 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003147 }
3148 usingCoords = scaledCoords;
3149 }
3150 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003151 // We don't want the dispatch target to know.
3152 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003153 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 scaledCoords[i].clear();
3155 }
3156 usingCoords = scaledCoords;
3157 }
3158 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003159
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003160 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161
3162 // Publish the motion event.
3163 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003164 .publishMotionEvent(dispatchEntry->seq,
3165 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003166 motionEntry.deviceId, motionEntry.source,
3167 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003168 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003169 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003171 motionEntry.edgeFlags, motionEntry.metaState,
3172 motionEntry.buttonState,
3173 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003174 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003175 motionEntry.xPrecision, motionEntry.yPrecision,
3176 motionEntry.xCursorPosition,
3177 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003178 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003179 dispatchEntry->displaySize.x,
3180 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 motionEntry.downTime, motionEntry.eventTime,
3182 motionEntry.pointerCount,
3183 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 break;
3185 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003186
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003187 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003189 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003190 focusEntry.id,
3191 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003192 mInTouchMode);
3193 break;
3194 }
3195
Prabir Pradhan99987712020-11-10 18:43:05 -08003196 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3197 const auto& captureEntry =
3198 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3199 status = connection->inputPublisher
3200 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3201 captureEntry.pointerCaptureEnabled);
3202 break;
3203 }
3204
arthurhungb89ccb02020-12-30 16:19:01 +08003205 case EventEntry::Type::DRAG: {
3206 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3207 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3208 dragEntry.id, dragEntry.x,
3209 dragEntry.y,
3210 dragEntry.isExiting);
3211 break;
3212 }
3213
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003214 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003215 case EventEntry::Type::DEVICE_RESET:
3216 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003217 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003218 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
3222
3223 // Check the result.
3224 if (status) {
3225 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003226 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 "This is unexpected because the wait queue is empty, so the pipe "
3229 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003230 "event to it, status=%s(%d)",
3231 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3232 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3234 } else {
3235 // Pipe is full and we are waiting for the app to finish process some events
3236 // before sending more events to it.
3237#if DEBUG_DISPATCH_CYCLE
3238 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 "waiting for the application to catch up",
3240 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
3243 } else {
3244 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003245 "status=%s(%d)",
3246 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3247 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3249 }
3250 return;
3251 }
3252
3253 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003254 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3255 connection->outboundQueue.end(),
3256 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003257 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003258 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003259 if (connection->responsive) {
3260 mAnrTracker.insert(dispatchEntry->timeoutTime,
3261 connection->inputChannel->getConnectionToken());
3262 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003263 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 }
3265}
3266
chaviw09c8d2d2020-08-24 15:48:26 -07003267std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3268 size_t size;
3269 switch (event.type) {
3270 case VerifiedInputEvent::Type::KEY: {
3271 size = sizeof(VerifiedKeyEvent);
3272 break;
3273 }
3274 case VerifiedInputEvent::Type::MOTION: {
3275 size = sizeof(VerifiedMotionEvent);
3276 break;
3277 }
3278 }
3279 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3280 return mHmacKeyManager.sign(start, size);
3281}
3282
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003283const std::array<uint8_t, 32> InputDispatcher::getSignature(
3284 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3285 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3286 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3287 // Only sign events up and down events as the purely move events
3288 // are tied to their up/down counterparts so signing would be redundant.
3289 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3290 verifiedEvent.actionMasked = actionMasked;
3291 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003292 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003293 }
3294 return INVALID_HMAC;
3295}
3296
3297const std::array<uint8_t, 32> InputDispatcher::getSignature(
3298 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3299 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3300 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3301 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003302 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003303}
3304
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003307 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308#if DEBUG_DISPATCH_CYCLE
3309 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311#endif
3312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 if (connection->status == Connection::STATUS_BROKEN ||
3314 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 return;
3316 }
3317
3318 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003319 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320}
3321
3322void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 const sp<Connection>& connection,
3324 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325#if DEBUG_DISPATCH_CYCLE
3326 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328#endif
3329
3330 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003331 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003332 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003333 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003334 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335
3336 // The connection appears to be unrecoverably broken.
3337 // Ignore already broken or zombie connections.
3338 if (connection->status == Connection::STATUS_NORMAL) {
3339 connection->status = Connection::STATUS_BROKEN;
3340
3341 if (notify) {
3342 // Notify other system components.
3343 onDispatchCycleBrokenLocked(currentTime, connection);
3344 }
3345 }
3346}
3347
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003348void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3349 while (!queue.empty()) {
3350 DispatchEntry* dispatchEntry = queue.front();
3351 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003352 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
3354}
3355
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003356void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003358 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 }
3360 delete dispatchEntry;
3361}
3362
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003363int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3364 std::scoped_lock _l(mLock);
3365 sp<Connection> connection = getConnectionLocked(connectionToken);
3366 if (connection == nullptr) {
3367 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3368 connectionToken.get(), events);
3369 return 0; // remove the callback
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003372 bool notify;
3373 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3374 if (!(events & ALOOPER_EVENT_INPUT)) {
3375 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3376 "events=0x%x",
3377 connection->getInputChannelName().c_str(), events);
3378 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
3380
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003381 nsecs_t currentTime = now();
3382 bool gotOne = false;
3383 status_t status = OK;
3384 for (;;) {
3385 Result<InputPublisher::ConsumerResponse> result =
3386 connection->inputPublisher.receiveConsumerResponse();
3387 if (!result.ok()) {
3388 status = result.error().code();
3389 break;
3390 }
3391
3392 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3393 const InputPublisher::Finished& finish =
3394 std::get<InputPublisher::Finished>(*result);
3395 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3396 finish.consumeTime);
3397 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003398 if (shouldReportMetricsForConnection(*connection)) {
3399 const InputPublisher::Timeline& timeline =
3400 std::get<InputPublisher::Timeline>(*result);
3401 mLatencyTracker
3402 .trackGraphicsLatency(timeline.inputEventId,
3403 connection->inputChannel->getConnectionToken(),
3404 std::move(timeline.graphicsTimeline));
3405 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003406 }
3407 gotOne = true;
3408 }
3409 if (gotOne) {
3410 runCommandsLockedInterruptible();
3411 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 return 1;
3413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 }
3415
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003416 notify = status != DEAD_OBJECT || !connection->monitor;
3417 if (notify) {
3418 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3419 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3420 status);
3421 }
3422 } else {
3423 // Monitor channels are never explicitly unregistered.
3424 // We do it automatically when the remote endpoint is closed so don't warn about them.
3425 const bool stillHaveWindowHandle =
3426 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3427 notify = !connection->monitor && stillHaveWindowHandle;
3428 if (notify) {
3429 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3430 connection->getInputChannelName().c_str(), events);
3431 }
3432 }
3433
3434 // Remove the channel.
3435 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3436 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437}
3438
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003439void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003441 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003442 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
3444}
3445
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003447 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003448 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3449 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3450}
3451
3452void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3453 const CancelationOptions& options,
3454 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3455 for (const auto& it : monitorsByDisplay) {
3456 const std::vector<Monitor>& monitors = it.second;
3457 for (const Monitor& monitor : monitors) {
3458 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003459 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003460 }
3461}
3462
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003464 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003465 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003466 if (connection == nullptr) {
3467 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003469
3470 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471}
3472
3473void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3474 const sp<Connection>& connection, const CancelationOptions& options) {
3475 if (connection->status == Connection::STATUS_BROKEN) {
3476 return;
3477 }
3478
3479 nsecs_t currentTime = now();
3480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003481 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003482 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003484 if (cancelationEvents.empty()) {
3485 return;
3486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003488 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3489 "with reality: %s, mode=%d.",
3490 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3491 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003493
3494 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003495 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003496 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3497 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003498 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003499 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003500 target.globalScaleFactor = windowInfo->globalScaleFactor;
3501 }
3502 target.inputChannel = connection->inputChannel;
3503 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3504
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003505 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003506 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003507 switch (cancelationEventEntry->type) {
3508 case EventEntry::Type::KEY: {
3509 logOutboundKeyDetails("cancel - ",
3510 static_cast<const KeyEntry&>(*cancelationEventEntry));
3511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003513 case EventEntry::Type::MOTION: {
3514 logOutboundMotionDetails("cancel - ",
3515 static_cast<const MotionEntry&>(*cancelationEventEntry));
3516 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003518 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003519 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3520 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003521 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003522 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003523 break;
3524 }
3525 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003526 case EventEntry::Type::DEVICE_RESET:
3527 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003528 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003529 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003530 break;
3531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003534 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3535 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003537
3538 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539}
3540
Svet Ganov5d3bc372020-01-26 23:11:07 -08003541void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3542 const sp<Connection>& connection) {
3543 if (connection->status == Connection::STATUS_BROKEN) {
3544 return;
3545 }
3546
3547 nsecs_t currentTime = now();
3548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003549 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003550 connection->inputState.synthesizePointerDownEvents(currentTime);
3551
3552 if (downEvents.empty()) {
3553 return;
3554 }
3555
3556#if DEBUG_OUTBOUND_EVENT_DETAILS
3557 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3558 connection->getInputChannelName().c_str(), downEvents.size());
3559#endif
3560
3561 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003562 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003563 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3564 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003565 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003566 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003567 target.globalScaleFactor = windowInfo->globalScaleFactor;
3568 }
3569 target.inputChannel = connection->inputChannel;
3570 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3571
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003572 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003573 switch (downEventEntry->type) {
3574 case EventEntry::Type::MOTION: {
3575 logOutboundMotionDetails("down - ",
3576 static_cast<const MotionEntry&>(*downEventEntry));
3577 break;
3578 }
3579
3580 case EventEntry::Type::KEY:
3581 case EventEntry::Type::FOCUS:
3582 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003583 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003584 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003585 case EventEntry::Type::SENSOR:
3586 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003587 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003588 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003589 break;
3590 }
3591 }
3592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003593 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3594 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003595 }
3596
3597 startDispatchCycleLocked(currentTime, connection);
3598}
3599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003600std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3601 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 ALOG_ASSERT(pointerIds.value != 0);
3603
3604 uint32_t splitPointerIndexMap[MAX_POINTERS];
3605 PointerProperties splitPointerProperties[MAX_POINTERS];
3606 PointerCoords splitPointerCoords[MAX_POINTERS];
3607
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003608 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 uint32_t splitPointerCount = 0;
3610
3611 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003614 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 uint32_t pointerId = uint32_t(pointerProperties.id);
3616 if (pointerIds.hasBit(pointerId)) {
3617 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3618 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3619 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003620 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 splitPointerCount += 1;
3622 }
3623 }
3624
3625 if (splitPointerCount != pointerIds.count()) {
3626 // This is bad. We are missing some of the pointers that we expected to deliver.
3627 // Most likely this indicates that we received an ACTION_MOVE events that has
3628 // different pointer ids than we expected based on the previous ACTION_DOWN
3629 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3630 // in this way.
3631 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003632 "we expected there to be %d pointers. This probably means we received "
3633 "a broken sequence of pointer ids from the input device.",
3634 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003635 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 }
3637
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003638 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003640 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3641 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3643 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003644 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 uint32_t pointerId = uint32_t(pointerProperties.id);
3646 if (pointerIds.hasBit(pointerId)) {
3647 if (pointerIds.count() == 1) {
3648 // The first/last pointer went down/up.
3649 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003650 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003651 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3652 ? AMOTION_EVENT_ACTION_CANCEL
3653 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 } else {
3655 // A secondary pointer went down/up.
3656 uint32_t splitPointerIndex = 0;
3657 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3658 splitPointerIndex += 1;
3659 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 action = maskedAction |
3661 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663 } else {
3664 // An unrelated pointer changed.
3665 action = AMOTION_EVENT_ACTION_MOVE;
3666 }
3667 }
3668
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003669 int32_t newId = mIdGenerator.nextId();
3670 if (ATRACE_ENABLED()) {
3671 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3672 ") to MotionEvent(id=0x%" PRIx32 ").",
3673 originalMotionEntry.id, newId);
3674 ATRACE_NAME(message.c_str());
3675 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 std::unique_ptr<MotionEntry> splitMotionEntry =
3677 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3678 originalMotionEntry.deviceId, originalMotionEntry.source,
3679 originalMotionEntry.displayId,
3680 originalMotionEntry.policyFlags, action,
3681 originalMotionEntry.actionButton,
3682 originalMotionEntry.flags, originalMotionEntry.metaState,
3683 originalMotionEntry.buttonState,
3684 originalMotionEntry.classification,
3685 originalMotionEntry.edgeFlags,
3686 originalMotionEntry.xPrecision,
3687 originalMotionEntry.yPrecision,
3688 originalMotionEntry.xCursorPosition,
3689 originalMotionEntry.yCursorPosition,
3690 originalMotionEntry.downTime, splitPointerCount,
3691 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003693 if (originalMotionEntry.injectionState) {
3694 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 splitMotionEntry->injectionState->refCount += 1;
3696 }
3697
3698 return splitMotionEntry;
3699}
3700
3701void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3702#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003703 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704#endif
3705
3706 bool needWake;
3707 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003708 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003710 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3711 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3712 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 } // release lock
3714
3715 if (needWake) {
3716 mLooper->wake();
3717 }
3718}
3719
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003720/**
3721 * If one of the meta shortcuts is detected, process them here:
3722 * Meta + Backspace -> generate BACK
3723 * Meta + Enter -> generate HOME
3724 * This will potentially overwrite keyCode and metaState.
3725 */
3726void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003727 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003728 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3729 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3730 if (keyCode == AKEYCODE_DEL) {
3731 newKeyCode = AKEYCODE_BACK;
3732 } else if (keyCode == AKEYCODE_ENTER) {
3733 newKeyCode = AKEYCODE_HOME;
3734 }
3735 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003736 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003737 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003738 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003739 keyCode = newKeyCode;
3740 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3741 }
3742 } else if (action == AKEY_EVENT_ACTION_UP) {
3743 // In order to maintain a consistent stream of up and down events, check to see if the key
3744 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3745 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003746 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003747 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003748 auto replacementIt = mReplacedKeys.find(replacement);
3749 if (replacementIt != mReplacedKeys.end()) {
3750 keyCode = replacementIt->second;
3751 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003752 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3753 }
3754 }
3755}
3756
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3758#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003759 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3760 "policyFlags=0x%x, action=0x%x, "
3761 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3762 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3763 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3764 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765#endif
3766 if (!validateKeyEvent(args->action)) {
3767 return;
3768 }
3769
3770 uint32_t policyFlags = args->policyFlags;
3771 int32_t flags = args->flags;
3772 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003773 // InputDispatcher tracks and generates key repeats on behalf of
3774 // whatever notifies it, so repeatCount should always be set to 0
3775 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3777 policyFlags |= POLICY_FLAG_VIRTUAL;
3778 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 if (policyFlags & POLICY_FLAG_FUNCTION) {
3781 metaState |= AMETA_FUNCTION_ON;
3782 }
3783
3784 policyFlags |= POLICY_FLAG_TRUSTED;
3785
Michael Wright78f24442014-08-06 15:55:28 -07003786 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003787 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003788
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003790 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003791 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3792 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
Michael Wright2b3c3302018-03-02 17:19:13 +00003794 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003796 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3797 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003798 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 bool needWake;
3802 { // acquire lock
3803 mLock.lock();
3804
3805 if (shouldSendKeyToInputFilterLocked(args)) {
3806 mLock.unlock();
3807
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003808 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3810 return; // event was consumed by the filter
3811 }
3812
3813 mLock.lock();
3814 }
3815
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003816 std::unique_ptr<KeyEntry> newEntry =
3817 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3818 args->displayId, policyFlags, args->action, flags,
3819 keyCode, args->scanCode, metaState, repeatCount,
3820 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003822 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 mLock.unlock();
3824 } // release lock
3825
3826 if (needWake) {
3827 mLooper->wake();
3828 }
3829}
3830
3831bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3832 return mInputFilterEnabled;
3833}
3834
3835void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3836#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003837 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3838 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003839 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3840 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003841 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003842 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3843 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3844 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3845 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 for (uint32_t i = 0; i < args->pointerCount; i++) {
3847 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 "x=%f, y=%f, pressure=%f, size=%f, "
3849 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3850 "orientation=%f",
3851 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3852 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3853 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3854 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3855 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3856 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3857 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3858 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3859 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3860 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 }
3862#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003863 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3864 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 return;
3866 }
3867
3868 uint32_t policyFlags = args->policyFlags;
3869 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003870
3871 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003872 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003873 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3874 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877
3878 bool needWake;
3879 { // acquire lock
3880 mLock.lock();
3881
3882 if (shouldSendMotionToInputFilterLocked(args)) {
3883 mLock.unlock();
3884
3885 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003886 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003887 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3888 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003889 args->metaState, args->buttonState, args->classification, transform,
3890 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003891 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3892 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3893 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894
3895 policyFlags |= POLICY_FLAG_FILTERED;
3896 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3897 return; // event was consumed by the filter
3898 }
3899
3900 mLock.lock();
3901 }
3902
3903 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003904 std::unique_ptr<MotionEntry> newEntry =
3905 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3906 args->source, args->displayId, policyFlags,
3907 args->action, args->actionButton, args->flags,
3908 args->metaState, args->buttonState,
3909 args->classification, args->edgeFlags,
3910 args->xPrecision, args->yPrecision,
3911 args->xCursorPosition, args->yCursorPosition,
3912 args->downTime, args->pointerCount,
3913 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003915 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 mLock.unlock();
3917 } // release lock
3918
3919 if (needWake) {
3920 mLooper->wake();
3921 }
3922}
3923
Chris Yef59a2f42020-10-16 12:55:26 -07003924void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3925#if DEBUG_INBOUND_EVENT_DETAILS
3926 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3927 " sensorType=%s",
3928 args->id, args->eventTime, args->deviceId, args->source,
3929 NamedEnum::string(args->sensorType).c_str());
3930#endif
3931
3932 bool needWake;
3933 { // acquire lock
3934 mLock.lock();
3935
3936 // Just enqueue a new sensor event.
3937 std::unique_ptr<SensorEntry> newEntry =
3938 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3939 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3940 args->sensorType, args->accuracy,
3941 args->accuracyChanged, args->values);
3942
3943 needWake = enqueueInboundEventLocked(std::move(newEntry));
3944 mLock.unlock();
3945 } // release lock
3946
3947 if (needWake) {
3948 mLooper->wake();
3949 }
3950}
3951
Chris Yefb552902021-02-03 17:18:37 -08003952void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3953#if DEBUG_INBOUND_EVENT_DETAILS
3954 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3955 args->deviceId, args->isOn);
3956#endif
3957 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3958}
3959
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003961 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962}
3963
3964void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3965#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003966 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 "switchMask=0x%08x",
3968 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969#endif
3970
3971 uint32_t policyFlags = args->policyFlags;
3972 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974}
3975
3976void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3977#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003978 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3979 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980#endif
3981
3982 bool needWake;
3983 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003984 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003986 std::unique_ptr<DeviceResetEntry> newEntry =
3987 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3988 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 } // release lock
3990
3991 if (needWake) {
3992 mLooper->wake();
3993 }
3994}
3995
Prabir Pradhan7e186182020-11-10 13:56:45 -08003996void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3997#if DEBUG_INBOUND_EVENT_DETAILS
3998 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3999 args->enabled ? "true" : "false");
4000#endif
4001
Prabir Pradhan99987712020-11-10 18:43:05 -08004002 bool needWake;
4003 { // acquire lock
4004 std::scoped_lock _l(mLock);
4005 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
4006 args->enabled);
4007 needWake = enqueueInboundEventLocked(std::move(entry));
4008 } // release lock
4009
4010 if (needWake) {
4011 mLooper->wake();
4012 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004013}
4014
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004015InputEventInjectionResult InputDispatcher::injectInputEvent(
4016 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4017 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018#if DEBUG_INBOUND_EVENT_DETAILS
4019 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004020 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4021 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004023 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024
4025 policyFlags |= POLICY_FLAG_INJECTED;
4026 if (hasInjectionPermission(injectorPid, injectorUid)) {
4027 policyFlags |= POLICY_FLAG_TRUSTED;
4028 }
4029
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004030 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004031 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4032 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4033 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4034 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4035 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004036 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004037 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004038 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004039 }
4040
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004041 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004044 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4045 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004046 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004047 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004050 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004051 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4052 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4053 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004054 int32_t keyCode = incomingKey.getKeyCode();
4055 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004056 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004057 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004058 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004059 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004060 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4061 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4062 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4065 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004066 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067
4068 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4069 android::base::Timer t;
4070 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4071 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4072 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4073 std::to_string(t.duration().count()).c_str());
4074 }
4075 }
4076
4077 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004078 std::unique_ptr<KeyEntry> injectedEntry =
4079 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004080 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081 incomingKey.getDisplayId(), policyFlags, action,
4082 flags, keyCode, incomingKey.getScanCode(), metaState,
4083 incomingKey.getRepeatCount(),
4084 incomingKey.getDownTime());
4085 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 }
4088
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004090 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4091 int32_t action = motionEvent.getAction();
4092 size_t pointerCount = motionEvent.getPointerCount();
4093 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4094 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004095 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004096 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004098 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004099 }
4100
4101 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004102 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004103 android::base::Timer t;
4104 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4105 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4106 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4107 std::to_string(t.duration().count()).c_str());
4108 }
4109 }
4110
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004111 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4112 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4113 }
4114
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004116 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4117 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004119 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4120 resolvedDeviceId, motionEvent.getSource(),
4121 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004122 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004123 motionEvent.getButtonState(),
4124 motionEvent.getClassification(),
4125 motionEvent.getEdgeFlags(),
4126 motionEvent.getXPrecision(),
4127 motionEvent.getYPrecision(),
4128 motionEvent.getRawXCursorPosition(),
4129 motionEvent.getRawYCursorPosition(),
4130 motionEvent.getDownTime(), uint32_t(pointerCount),
4131 pointerProperties, samplePointerCoords,
4132 motionEvent.getXOffset(),
4133 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004134 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004135 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 sampleEventTimes += 1;
4137 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004138 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004139 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4140 resolvedDeviceId, motionEvent.getSource(),
4141 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004142 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004143 motionEvent.getMetaState(),
4144 motionEvent.getButtonState(),
4145 motionEvent.getClassification(),
4146 motionEvent.getEdgeFlags(),
4147 motionEvent.getXPrecision(),
4148 motionEvent.getYPrecision(),
4149 motionEvent.getRawXCursorPosition(),
4150 motionEvent.getRawYCursorPosition(),
4151 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004152 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004153 samplePointerCoords, motionEvent.getXOffset(),
4154 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004155 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156 }
4157 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004161 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004162 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
4164
4165 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004166 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 injectionState->injectionIsAsync = true;
4168 }
4169
4170 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004171 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
4173 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004174 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004175 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004176 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 }
4178
4179 mLock.unlock();
4180
4181 if (needWake) {
4182 mLooper->wake();
4183 }
4184
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004185 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004187 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004189 if (syncMode == InputEventInjectionSync::NONE) {
4190 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 } else {
4192 for (;;) {
4193 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004194 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 }
4197
4198 nsecs_t remainingTimeout = endTime - now();
4199 if (remainingTimeout <= 0) {
4200#if DEBUG_INJECTION
4201 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004204 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 break;
4206 }
4207
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004208 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 }
4210
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004211 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4212 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 while (injectionState->pendingForegroundDispatches != 0) {
4214#if DEBUG_INJECTION
4215 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217#endif
4218 nsecs_t remainingTimeout = endTime - now();
4219 if (remainingTimeout <= 0) {
4220#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004221 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4222 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004224 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 break;
4226 }
4227
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004228 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 }
4230 }
4231 }
4232
4233 injectionState->release();
4234 } // release lock
4235
4236#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004237 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239#endif
4240
4241 return injectionResult;
4242}
4243
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004244std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004245 std::array<uint8_t, 32> calculatedHmac;
4246 std::unique_ptr<VerifiedInputEvent> result;
4247 switch (event.getType()) {
4248 case AINPUT_EVENT_TYPE_KEY: {
4249 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4250 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4251 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004252 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004253 break;
4254 }
4255 case AINPUT_EVENT_TYPE_MOTION: {
4256 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4257 VerifiedMotionEvent verifiedMotionEvent =
4258 verifiedMotionEventFromMotionEvent(motionEvent);
4259 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004260 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004261 break;
4262 }
4263 default: {
4264 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4265 return nullptr;
4266 }
4267 }
4268 if (calculatedHmac == INVALID_HMAC) {
4269 return nullptr;
4270 }
4271 if (calculatedHmac != event.getHmac()) {
4272 return nullptr;
4273 }
4274 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004275}
4276
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 return injectorUid == 0 ||
4279 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280}
4281
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004283 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004284 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 if (injectionState) {
4286#if DEBUG_INJECTION
4287 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004288 "injectorPid=%d, injectorUid=%d",
4289 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290#endif
4291
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004292 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 // Log the outcome since the injector did not wait for the injection result.
4294 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004295 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 ALOGV("Asynchronous input event injection succeeded.");
4297 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004298 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 ALOGW("Asynchronous input event injection failed.");
4300 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004302 ALOGW("Asynchronous input event injection permission denied.");
4303 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004304 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004305 ALOGW("Asynchronous input event injection timed out.");
4306 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 case InputEventInjectionResult::PENDING:
4308 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 }
4312
4313 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004314 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 }
4316}
4317
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004318void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4319 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 if (injectionState) {
4321 injectionState->pendingForegroundDispatches += 1;
4322 }
4323}
4324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004325void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4326 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 if (injectionState) {
4328 injectionState->pendingForegroundDispatches -= 1;
4329
4330 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004331 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 }
4333 }
4334}
4335
chaviw3277faf2021-05-19 16:45:23 -05004336const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004337 int32_t displayId) const {
chaviw3277faf2021-05-19 16:45:23 -05004338 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004339 auto it = mWindowHandlesByDisplay.find(displayId);
4340 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004341}
4342
chaviw3277faf2021-05-19 16:45:23 -05004343sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004344 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004345 if (windowHandleToken == nullptr) {
4346 return nullptr;
4347 }
4348
Arthur Hungb92218b2018-08-14 12:00:21 +08004349 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004350 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4351 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004352 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004353 return windowHandle;
4354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 }
4356 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004357 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358}
4359
chaviw3277faf2021-05-19 16:45:23 -05004360sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4361 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004362 if (windowHandleToken == nullptr) {
4363 return nullptr;
4364 }
4365
chaviw3277faf2021-05-19 16:45:23 -05004366 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004367 if (windowHandle->getToken() == windowHandleToken) {
4368 return windowHandle;
4369 }
4370 }
4371 return nullptr;
4372}
4373
chaviw3277faf2021-05-19 16:45:23 -05004374sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4375 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004376 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004377 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4378 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004379 if (handle->getId() == windowHandle->getId() &&
4380 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004381 if (windowHandle->getInfo()->displayId != it.first) {
4382 ALOGE("Found window %s in display %" PRId32
4383 ", but it should belong to display %" PRId32,
4384 windowHandle->getName().c_str(), it.first,
4385 windowHandle->getInfo()->displayId);
4386 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004387 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 }
4390 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004391 return nullptr;
4392}
4393
chaviw3277faf2021-05-19 16:45:23 -05004394sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004395 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4396 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397}
4398
chaviw3277faf2021-05-19 16:45:23 -05004399bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004400 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4401 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004402 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004403 if (connection != nullptr && noInputChannel) {
4404 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4405 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4406 return false;
4407 }
4408
4409 if (connection == nullptr) {
4410 if (!noInputChannel) {
4411 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4412 }
4413 return false;
4414 }
4415 if (!connection->responsive) {
4416 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4417 return false;
4418 }
4419 return true;
4420}
4421
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004422std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4423 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004424 auto connectionIt = mConnectionsByToken.find(token);
4425 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004426 return nullptr;
4427 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004428 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004429}
4430
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004431void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw3277faf2021-05-19 16:45:23 -05004432 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4433 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004434 // Remove all handles on a display if there are no windows left.
4435 mWindowHandlesByDisplay.erase(displayId);
4436 return;
4437 }
4438
4439 // Since we compare the pointer of input window handles across window updates, we need
4440 // to make sure the handle object for the same window stays unchanged across updates.
chaviw3277faf2021-05-19 16:45:23 -05004441 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4442 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4443 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004444 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004445 }
4446
chaviw3277faf2021-05-19 16:45:23 -05004447 std::vector<sp<WindowInfoHandle>> newHandles;
4448 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw3277faf2021-05-19 16:45:23 -05004449 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004450 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4451 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4452 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004453 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4454 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4455 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004456 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004457 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004458 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004459 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004460 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004461 }
4462
4463 if (info->displayId != displayId) {
4464 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4465 handle->getName().c_str(), displayId, info->displayId);
4466 continue;
4467 }
4468
Robert Carredd13602020-04-13 17:24:34 -07004469 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4470 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw3277faf2021-05-19 16:45:23 -05004471 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004472 oldHandle->updateFrom(handle);
4473 newHandles.push_back(oldHandle);
4474 } else {
4475 newHandles.push_back(handle);
4476 }
4477 }
4478
4479 // Insert or replace
4480 mWindowHandlesByDisplay[displayId] = newHandles;
4481}
4482
Arthur Hung72d8dc32020-03-28 00:48:39 +00004483void InputDispatcher::setInputWindows(
chaviw3277faf2021-05-19 16:45:23 -05004484 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004485 { // acquire lock
4486 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004487 for (const auto& [displayId, handles] : handlesPerDisplay) {
4488 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004489 }
4490 }
4491 // Wake up poll loop since it may need to make new input dispatching choices.
4492 mLooper->wake();
4493}
4494
Arthur Hungb92218b2018-08-14 12:00:21 +08004495/**
4496 * Called from InputManagerService, update window handle list by displayId that can receive input.
4497 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4498 * If set an empty list, remove all handles from the specific display.
4499 * For focused handle, check if need to change and send a cancel event to previous one.
4500 * For removed handle, check if need to send a cancel event if already in touch.
4501 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004502void InputDispatcher::setInputWindowsLocked(
chaviw3277faf2021-05-19 16:45:23 -05004503 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004504 if (DEBUG_FOCUS) {
4505 std::string windowList;
chaviw3277faf2021-05-19 16:45:23 -05004506 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004507 windowList += iwh->getName() + " ";
4508 }
4509 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004512 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw3277faf2021-05-19 16:45:23 -05004513 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004514 const bool noInputWindow =
chaviw3277faf2021-05-19 16:45:23 -05004515 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004516 if (noInputWindow && window->getToken() != nullptr) {
4517 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4518 window->getName().c_str());
4519 window->releaseChannel();
4520 }
4521 }
4522
Arthur Hung72d8dc32020-03-28 00:48:39 +00004523 // Copy old handles for release if they are no longer present.
chaviw3277faf2021-05-19 16:45:23 -05004524 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004526 // Save the old windows' orientation by ID before it gets updated.
4527 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw3277faf2021-05-19 16:45:23 -05004528 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004529 oldWindowOrientations.emplace(handle->getId(),
4530 handle->getInfo()->transform.getOrientation());
4531 }
4532
chaviw3277faf2021-05-19 16:45:23 -05004533 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004534
chaviw3277faf2021-05-19 16:45:23 -05004535 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004536 if (mLastHoverWindowHandle &&
4537 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4538 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004539 mLastHoverWindowHandle = nullptr;
4540 }
4541
Vishnu Nairc519ff72021-01-21 08:23:08 -08004542 std::optional<FocusResolver::FocusChanges> changes =
4543 mFocusResolver.setInputWindows(displayId, windowHandles);
4544 if (changes) {
4545 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004548 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4549 mTouchStatesByDisplay.find(displayId);
4550 if (stateIt != mTouchStatesByDisplay.end()) {
4551 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004552 for (size_t i = 0; i < state.windows.size();) {
4553 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004554 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004555 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004556 ALOGD("Touched window was removed: %s in display %" PRId32,
4557 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004558 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004559 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004560 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4561 if (touchedInputChannel != nullptr) {
4562 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4563 "touched window was removed");
4564 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004566 state.windows.erase(state.windows.begin() + i);
4567 } else {
4568 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 }
4570 }
arthurhungb89ccb02020-12-30 16:19:01 +08004571
arthurhung6d4bed92021-03-17 11:59:33 +08004572 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004573 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004574 if (mDragState &&
4575 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004576 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004577 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004578 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004579 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004580
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004581 if (isPerWindowInputRotationEnabled()) {
4582 // Determine if the orientation of any of the input windows have changed, and cancel all
4583 // pointer events if necessary.
chaviw3277faf2021-05-19 16:45:23 -05004584 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4585 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004586 if (newWindowHandle != nullptr &&
4587 newWindowHandle->getInfo()->transform.getOrientation() !=
4588 oldWindowOrientations[oldWindowHandle->getId()]) {
4589 std::shared_ptr<InputChannel> inputChannel =
4590 getInputChannelLocked(newWindowHandle->getToken());
4591 if (inputChannel != nullptr) {
4592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4593 "touched window's orientation changed");
4594 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4595 }
4596 }
4597 }
4598 }
4599
Arthur Hung72d8dc32020-03-28 00:48:39 +00004600 // Release information for windows that are no longer present.
4601 // This ensures that unused input channels are released promptly.
4602 // Otherwise, they might stick around until the window handle is destroyed
4603 // which might not happen until the next GC.
chaviw3277faf2021-05-19 16:45:23 -05004604 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004605 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606 if (DEBUG_FOCUS) {
4607 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004608 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004609 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004610 // To avoid making too many calls into the compat framework, only
4611 // check for window flags when windows are going away.
4612 // TODO(b/157929241) : delete this. This is only needed temporarily
4613 // in order to gather some data about the flag usage
chaviw3277faf2021-05-19 16:45:23 -05004614 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004615 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4616 oldWindowHandle->getName().c_str());
4617 if (mCompatService != nullptr) {
4618 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4619 oldWindowHandle->getInfo()->ownerUid);
4620 }
4621 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004622 }
chaviw291d88a2019-02-14 10:33:58 -08004623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624}
4625
4626void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004627 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004628 if (DEBUG_FOCUS) {
4629 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4630 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4631 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004632 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004633 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004634 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 } // release lock
4636
4637 // Wake up poll loop since it may need to make new input dispatching choices.
4638 mLooper->wake();
4639}
4640
Vishnu Nair599f1412021-06-21 10:39:58 -07004641void InputDispatcher::setFocusedApplicationLocked(
4642 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4643 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4644 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4645
4646 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4647 return; // This application is already focused. No need to wake up or change anything.
4648 }
4649
4650 // Set the new application handle.
4651 if (inputApplicationHandle != nullptr) {
4652 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4653 } else {
4654 mFocusedApplicationHandlesByDisplay.erase(displayId);
4655 }
4656
4657 // No matter what the old focused application was, stop waiting on it because it is
4658 // no longer focused.
4659 resetNoFocusedWindowTimeoutLocked();
4660}
4661
Tiger Huang721e26f2018-07-24 22:26:19 +08004662/**
4663 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4664 * the display not specified.
4665 *
4666 * We track any unreleased events for each window. If a window loses the ability to receive the
4667 * released event, we will send a cancel event to it. So when the focused display is changed, we
4668 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4669 * display. The display-specified events won't be affected.
4670 */
4671void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004672 if (DEBUG_FOCUS) {
4673 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4674 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004675 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004676 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004677
4678 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004679 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004680 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004681 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004682 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004683 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004684 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 CancelationOptions
4686 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4687 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004688 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004689 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4690 }
4691 }
4692 mFocusedDisplayId = displayId;
4693
Chris Ye3c2d6f52020-08-09 10:39:48 -07004694 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004695 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004696 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004697
Vishnu Nairad321cd2020-08-20 16:40:21 -07004698 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004699 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004700 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004701 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004702 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004703 }
4704 }
4705 }
4706
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004707 if (DEBUG_FOCUS) {
4708 logDispatchStateLocked();
4709 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004710 } // release lock
4711
4712 // Wake up poll loop since it may need to make new input dispatching choices.
4713 mLooper->wake();
4714}
4715
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004717 if (DEBUG_FOCUS) {
4718 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720
4721 bool changed;
4722 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004723 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
4725 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4726 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729
4730 if (mDispatchEnabled && !enabled) {
4731 resetAndDropEverythingLocked("dispatcher is being disabled");
4732 }
4733
4734 mDispatchEnabled = enabled;
4735 mDispatchFrozen = frozen;
4736 changed = true;
4737 } else {
4738 changed = false;
4739 }
4740
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004741 if (DEBUG_FOCUS) {
4742 logDispatchStateLocked();
4743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 } // release lock
4745
4746 if (changed) {
4747 // Wake up poll loop since it may need to make new input dispatching choices.
4748 mLooper->wake();
4749 }
4750}
4751
4752void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004753 if (DEBUG_FOCUS) {
4754 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756
4757 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004758 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759
4760 if (mInputFilterEnabled == enabled) {
4761 return;
4762 }
4763
4764 mInputFilterEnabled = enabled;
4765 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4766 } // release lock
4767
4768 // Wake up poll loop since there might be work to do to drop everything.
4769 mLooper->wake();
4770}
4771
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004772void InputDispatcher::setInTouchMode(bool inTouchMode) {
4773 std::scoped_lock lock(mLock);
4774 mInTouchMode = inTouchMode;
4775}
4776
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004777void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4778 if (opacity < 0 || opacity > 1) {
4779 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4780 return;
4781 }
4782
4783 std::scoped_lock lock(mLock);
4784 mMaximumObscuringOpacityForTouch = opacity;
4785}
4786
4787void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4788 std::scoped_lock lock(mLock);
4789 mBlockUntrustedTouchesMode = mode;
4790}
4791
arthurhungb89ccb02020-12-30 16:19:01 +08004792bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4793 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004794 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004795 if (DEBUG_FOCUS) {
4796 ALOGD("Trivial transfer to same window.");
4797 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004798 return true;
4799 }
4800
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004802 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
chaviw3277faf2021-05-19 16:45:23 -05004804 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4805 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004806 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004807 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 return false;
4809 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004810 if (DEBUG_FOCUS) {
4811 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4812 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004815 if (DEBUG_FOCUS) {
4816 ALOGD("Cannot transfer focus because windows are on different displays.");
4817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 return false;
4819 }
4820
4821 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004822 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4823 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004824 for (size_t i = 0; i < state.windows.size(); i++) {
4825 const TouchedWindow& touchedWindow = state.windows[i];
4826 if (touchedWindow.windowHandle == fromWindowHandle) {
4827 int32_t oldTargetFlags = touchedWindow.targetFlags;
4828 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004830 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 int32_t newTargetFlags = oldTargetFlags &
4833 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4834 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004835 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836
arthurhungb89ccb02020-12-30 16:19:01 +08004837 // Store the dragging window.
4838 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004839 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004840 }
4841
Jeff Brownf086ddb2014-02-11 14:28:48 -08004842 found = true;
4843 goto Found;
4844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004850 if (DEBUG_FOCUS) {
4851 ALOGD("Focus transfer failed because from window did not have focus.");
4852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 return false;
4854 }
4855
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004856 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4857 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004858 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004859 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860 CancelationOptions
4861 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4862 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004864 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004867 if (DEBUG_FOCUS) {
4868 logDispatchStateLocked();
4869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 } // release lock
4871
4872 // Wake up poll loop since it may need to make new input dispatching choices.
4873 mLooper->wake();
4874 return true;
4875}
4876
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004877// Binder call
4878bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4879 sp<IBinder> fromToken;
4880 { // acquire lock
4881 std::scoped_lock _l(mLock);
4882
chaviw3277faf2021-05-19 16:45:23 -05004883 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004884 if (toWindowHandle == nullptr) {
4885 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4886 return false;
4887 }
4888
4889 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4890
4891 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4892 if (touchStateIt == mTouchStatesByDisplay.end()) {
4893 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4894 displayId);
4895 return false;
4896 }
4897
4898 TouchState& state = touchStateIt->second;
4899 if (state.windows.size() != 1) {
4900 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4901 state.windows.size());
4902 return false;
4903 }
4904 const TouchedWindow& touchedWindow = state.windows[0];
4905 fromToken = touchedWindow.windowHandle->getToken();
4906 } // release lock
4907
4908 return transferTouchFocus(fromToken, destChannelToken);
4909}
4910
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004912 if (DEBUG_FOCUS) {
4913 ALOGD("Resetting and dropping all events (%s).", reason);
4914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
4916 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4917 synthesizeCancelationEventsForAllConnectionsLocked(options);
4918
4919 resetKeyRepeatLocked();
4920 releasePendingEventLocked();
4921 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004922 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004925 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004927 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928}
4929
4930void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004931 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 dumpDispatchStateLocked(dump);
4933
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004934 std::istringstream stream(dump);
4935 std::string line;
4936
4937 while (std::getline(stream, line, '\n')) {
4938 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 }
4940}
4941
Prabir Pradhan99987712020-11-10 18:43:05 -08004942std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4943 std::string dump;
4944
4945 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4946 toString(mFocusedWindowRequestedPointerCapture));
4947
4948 std::string windowName = "None";
4949 if (mWindowTokenWithPointerCapture) {
chaviw3277faf2021-05-19 16:45:23 -05004950 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004951 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4952 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4953 : "token has capture without window";
4954 }
4955 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4956
4957 return dump;
4958}
4959
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004960void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004961 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4962 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4963 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004964 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
Tiger Huang721e26f2018-07-24 22:26:19 +08004966 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4967 dump += StringPrintf(INDENT "FocusedApplications:\n");
4968 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4969 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004970 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004971 const std::chrono::duration timeout =
4972 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004973 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004974 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004975 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004978 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004980
Vishnu Nairc519ff72021-01-21 08:23:08 -08004981 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004982 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004984 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004985 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004986 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4987 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004988 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 state.displayId, toString(state.down), toString(state.split),
4990 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004991 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004992 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004993 for (size_t i = 0; i < state.windows.size(); i++) {
4994 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 dump += StringPrintf(INDENT4
4996 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4997 i, touchedWindow.windowHandle->getName().c_str(),
4998 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004999 }
5000 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005001 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005002 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005003 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005004 dump += INDENT3 "Portal windows:\n";
5005 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005006 const sp<WindowInfoHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5008 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005009 }
5010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005013 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015
arthurhung6d4bed92021-03-17 11:59:33 +08005016 if (mDragState) {
5017 dump += StringPrintf(INDENT "DragState:\n");
5018 mDragState->dump(dump, INDENT2);
5019 }
5020
Arthur Hungb92218b2018-08-14 12:00:21 +08005021 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05005023 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005024 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005025 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005026 dump += INDENT2 "Windows:\n";
5027 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005028 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5029 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005031 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005032 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005033 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005034 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005035 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005036 "applicationInfo.name=%s, "
5037 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005038 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005039 i, windowInfo->name.c_str(), windowInfo->id,
5040 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005042 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005043 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005044 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005045 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005046 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005047 windowInfo->frameLeft, windowInfo->frameTop,
5048 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005049 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005050 windowInfo->applicationInfo.name.c_str(),
5051 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005052 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005053 dump += StringPrintf(", inputFeatures=%s",
5054 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005055 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005056 "ms, trustedOverlay=%s, hasToken=%s, "
5057 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005059 millis(windowInfo->dispatchingTimeout),
5060 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005061 toString(windowInfo->token != nullptr),
5062 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005063 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005064 }
5065 } else {
5066 dump += INDENT2 "Windows: <none>\n";
5067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 }
5069 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005070 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
5072
Michael Wright3dd60e22019-03-27 22:06:44 +00005073 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005074 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 const std::vector<Monitor>& monitors = it.second;
5076 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5077 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005078 }
5079 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005080 const std::vector<Monitor>& monitors = it.second;
5081 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5082 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005085 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087
5088 nsecs_t currentTime = now();
5089
5090 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005091 if (!mRecentQueue.empty()) {
5092 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005093 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005094 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005095 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005096 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 }
5098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101
5102 // Dump event currently being dispatched.
5103 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005104 dump += INDENT "PendingEvent:\n";
5105 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005106 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005107 dump += StringPrintf(", age=%" PRId64 "ms\n",
5108 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005110 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 }
5112
5113 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005114 if (!mInboundQueue.empty()) {
5115 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005116 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005117 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005118 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005119 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 }
5121 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005122 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 }
5124
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005125 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005126 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005127 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5128 const KeyReplacement& replacement = pair.first;
5129 int32_t newKeyCode = pair.second;
5130 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005131 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005132 }
5133 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005134 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005135 }
5136
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005137 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005138 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005139 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005141 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005142 connection->inputChannel->getFd().get(),
5143 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005144 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005145 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005147 if (!connection->outboundQueue.empty()) {
5148 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5149 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005150 dump += dumpQueue(connection->outboundQueue, currentTime);
5151
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005153 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005156 if (!connection->waitQueue.empty()) {
5157 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5158 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005159 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005161 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163 }
5164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167
5168 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5170 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005175 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005176 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5177 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5178 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005179 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005180 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
Michael Wright3dd60e22019-03-27 22:06:44 +00005183void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5184 const size_t numMonitors = monitors.size();
5185 for (size_t i = 0; i < numMonitors; i++) {
5186 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005187 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005188 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5189 dump += "\n";
5190 }
5191}
5192
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005193class LooperEventCallback : public LooperCallback {
5194public:
5195 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5196 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5197
5198private:
5199 std::function<int(int events)> mCallback;
5200};
5201
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005202Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005203#if DEBUG_CHANNEL_CREATION
5204 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205#endif
5206
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005207 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005208 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005209 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005210
5211 if (result) {
5212 return base::Error(result) << "Failed to open input channel pair with name " << name;
5213 }
5214
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005216 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005217 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005218 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005219 sp<Connection> connection =
5220 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005222 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5223 ALOGE("Created a new connection, but the token %p is already known", token.get());
5224 }
5225 mConnectionsByToken.emplace(token, connection);
5226
5227 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5228 this, std::placeholders::_1, token);
5229
5230 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 } // release lock
5232
5233 // Wake the looper because some connections have changed.
5234 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005235 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236}
5237
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005238Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5239 bool isGestureMonitor,
5240 const std::string& name,
5241 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005242 std::shared_ptr<InputChannel> serverChannel;
5243 std::unique_ptr<InputChannel> clientChannel;
5244 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5245 if (result) {
5246 return base::Error(result) << "Failed to open input channel pair with name " << name;
5247 }
5248
Michael Wright3dd60e22019-03-27 22:06:44 +00005249 { // acquire lock
5250 std::scoped_lock _l(mLock);
5251
5252 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005253 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5254 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005255 }
5256
Garfield Tan15601662020-09-22 15:32:38 -07005257 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005258 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005259 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005260
5261 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5262 ALOGE("Created a new connection, but the token %p is already known", token.get());
5263 }
5264 mConnectionsByToken.emplace(token, connection);
5265 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5266 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 auto& monitorsByDisplay =
5269 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005270 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005271
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005273 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5274 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005275 }
Garfield Tan15601662020-09-22 15:32:38 -07005276
Michael Wright3dd60e22019-03-27 22:06:44 +00005277 // Wake the looper because some connections have changed.
5278 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005279 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005280}
5281
Garfield Tan15601662020-09-22 15:32:38 -07005282status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005284 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285
Garfield Tan15601662020-09-22 15:32:38 -07005286 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 if (status) {
5288 return status;
5289 }
5290 } // release lock
5291
5292 // Wake the poll loop because removing the connection may have changed the current
5293 // synchronization state.
5294 mLooper->wake();
5295 return OK;
5296}
5297
Garfield Tan15601662020-09-22 15:32:38 -07005298status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5299 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005300 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005301 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005302 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 return BAD_VALUE;
5304 }
5305
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005306 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005307
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005309 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005312 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 nsecs_t currentTime = now();
5315 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5316
5317 connection->status = Connection::STATUS_ZOMBIE;
5318 return OK;
5319}
5320
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005321void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5322 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5323 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005324}
5325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005326void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005327 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005328 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005329 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005330 std::vector<Monitor>& monitors = it->second;
5331 const size_t numMonitors = monitors.size();
5332 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005333 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005334 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5335 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005336 monitors.erase(monitors.begin() + i);
5337 break;
5338 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005339 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 if (monitors.empty()) {
5341 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005342 } else {
5343 ++it;
5344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 }
5346}
5347
Michael Wright3dd60e22019-03-27 22:06:44 +00005348status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5349 { // acquire lock
5350 std::scoped_lock _l(mLock);
5351 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5352
5353 if (!foundDisplayId) {
5354 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5355 return BAD_VALUE;
5356 }
5357 int32_t displayId = foundDisplayId.value();
5358
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005359 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5360 mTouchStatesByDisplay.find(displayId);
5361 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005362 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5363 return BAD_VALUE;
5364 }
5365
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005366 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005367 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005368 std::optional<int32_t> foundDeviceId;
5369 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005370 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005371 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005372 foundDeviceId = state.deviceId;
5373 }
5374 }
5375 if (!foundDeviceId || !state.down) {
5376 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005377 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005378 return BAD_VALUE;
5379 }
5380 int32_t deviceId = foundDeviceId.value();
5381
5382 // Send cancel events to all the input channels we're stealing from.
5383 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 options.deviceId = deviceId;
5386 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005387 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005388 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005389 std::shared_ptr<InputChannel> channel =
5390 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005391 if (channel != nullptr) {
5392 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005393 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005394 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005395 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005396 canceledWindows += "]";
5397 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5398 canceledWindows.c_str());
5399
Michael Wright3dd60e22019-03-27 22:06:44 +00005400 // Then clear the current touch state so we stop dispatching to them as well.
5401 state.filterNonMonitors();
5402 }
5403 return OK;
5404}
5405
Prabir Pradhan99987712020-11-10 18:43:05 -08005406void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5407 { // acquire lock
5408 std::scoped_lock _l(mLock);
5409 if (DEBUG_FOCUS) {
chaviw3277faf2021-05-19 16:45:23 -05005410 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005411 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5412 windowHandle != nullptr ? windowHandle->getName().c_str()
5413 : "token without window");
5414 }
5415
Vishnu Nairc519ff72021-01-21 08:23:08 -08005416 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005417 if (focusedToken != windowToken) {
5418 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5419 enabled ? "enable" : "disable");
5420 return;
5421 }
5422
5423 if (enabled == mFocusedWindowRequestedPointerCapture) {
5424 ALOGW("Ignoring request to %s Pointer Capture: "
5425 "window has %s requested pointer capture.",
5426 enabled ? "enable" : "disable", enabled ? "already" : "not");
5427 return;
5428 }
5429
5430 mFocusedWindowRequestedPointerCapture = enabled;
5431 setPointerCaptureLocked(enabled);
5432 } // release lock
5433
5434 // Wake the thread to process command entries.
5435 mLooper->wake();
5436}
5437
Michael Wright3dd60e22019-03-27 22:06:44 +00005438std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5439 const sp<IBinder>& token) {
5440 for (const auto& it : mGestureMonitorsByDisplay) {
5441 const std::vector<Monitor>& monitors = it.second;
5442 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005443 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005444 return it.first;
5445 }
5446 }
5447 }
5448 return std::nullopt;
5449}
5450
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005451std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5452 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5453 if (gesturePid.has_value()) {
5454 return gesturePid;
5455 }
5456 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5457}
5458
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005459sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005460 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005461 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005462 }
5463
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005464 for (const auto& [token, connection] : mConnectionsByToken) {
5465 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005466 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 }
5468 }
Robert Carr4e670e52018-08-15 13:26:12 -07005469
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005470 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471}
5472
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005473std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5474 sp<Connection> connection = getConnectionLocked(connectionToken);
5475 if (connection == nullptr) {
5476 return "<nullptr>";
5477 }
5478 return connection->getInputChannelName();
5479}
5480
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005481void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005482 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005483 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005484}
5485
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005486void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5487 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005488 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005489 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5490 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 commandEntry->connection = connection;
5492 commandEntry->eventTime = currentTime;
5493 commandEntry->seq = seq;
5494 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005495 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005496 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497}
5498
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005499void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5500 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005502 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005504 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5505 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005507 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508}
5509
Vishnu Nairad321cd2020-08-20 16:40:21 -07005510void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5511 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005512 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5513 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005514 commandEntry->oldToken = oldToken;
5515 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005516 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005517}
5518
arthurhungf452d0b2021-01-06 00:19:52 +08005519void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5520 std::unique_ptr<CommandEntry> commandEntry =
5521 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5522 commandEntry->newToken = token;
5523 commandEntry->x = x;
5524 commandEntry->y = y;
5525 postCommandLocked(std::move(commandEntry));
5526}
5527
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005528void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5529 if (connection == nullptr) {
5530 LOG_ALWAYS_FATAL("Caller must check for nullness");
5531 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005532 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5533 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005534 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005535 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005536 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005537 return;
5538 }
5539 /**
5540 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5541 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5542 * has changed. This could cause newer entries to time out before the already dispatched
5543 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5544 * processes the events linearly. So providing information about the oldest entry seems to be
5545 * most useful.
5546 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005547 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005548 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5549 std::string reason =
5550 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005551 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005552 ns2ms(currentWait),
5553 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005554 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005555 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005556
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005557 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5558
5559 // Stop waking up for events on this connection, it is already unresponsive
5560 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005561}
5562
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005563void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5564 std::string reason =
5565 StringPrintf("%s does not have a focused window", application->getName().c_str());
5566 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005567
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005568 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5569 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5570 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005571 postCommandLocked(std::move(commandEntry));
5572}
5573
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005574void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5575 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5576 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5577 commandEntry->obscuringPackage = obscuringPackage;
5578 postCommandLocked(std::move(commandEntry));
5579}
5580
chaviw3277faf2021-05-19 16:45:23 -05005581void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005582 const std::string& reason) {
5583 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5584 updateLastAnrStateLocked(windowLabel, reason);
5585}
5586
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005587void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5588 const std::string& reason) {
5589 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005590 updateLastAnrStateLocked(windowLabel, reason);
5591}
5592
5593void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5594 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005596 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 struct tm tm;
5598 localtime_r(&t, &tm);
5599 char timestr[64];
5600 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005601 mLastAnrState.clear();
5602 mLastAnrState += INDENT "ANR:\n";
5603 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005604 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5605 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005606 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607}
5608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005609void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 mLock.unlock();
5611
5612 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5613
5614 mLock.lock();
5615}
5616
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005617void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 sp<Connection> connection = commandEntry->connection;
5619
5620 if (connection->status != Connection::STATUS_ZOMBIE) {
5621 mLock.unlock();
5622
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005623 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624
5625 mLock.lock();
5626 }
5627}
5628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005629void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005630 sp<IBinder> oldToken = commandEntry->oldToken;
5631 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005632 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005633 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005634 mLock.lock();
5635}
5636
arthurhungf452d0b2021-01-06 00:19:52 +08005637void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5638 sp<IBinder> newToken = commandEntry->newToken;
5639 mLock.unlock();
5640 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5641 mLock.lock();
5642}
5643
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005644void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005646
5647 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5648
5649 mLock.lock();
5650}
5651
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005652void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005653 mLock.unlock();
5654
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005655 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656
5657 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005658}
5659
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005660void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005661 mLock.unlock();
5662
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005663 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5664
5665 mLock.lock();
5666}
5667
5668void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5669 mLock.unlock();
5670
5671 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5672
5673 mLock.lock();
5674}
5675
5676void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5677 mLock.unlock();
5678
5679 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005680
5681 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005682}
5683
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005684void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5685 mLock.unlock();
5686
5687 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5688
5689 mLock.lock();
5690}
5691
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5693 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005694 KeyEntry& entry = *(commandEntry->keyEntry);
5695 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696
5697 mLock.unlock();
5698
Michael Wright2b3c3302018-03-02 17:19:13 +00005699 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005700 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005701 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005702 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5703 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005704 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706
5707 mLock.lock();
5708
5709 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005710 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005712 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005714 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5715 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717}
5718
chaviwfd6d3512019-03-25 13:23:49 -07005719void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5720 mLock.unlock();
5721 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5722 mLock.lock();
5723}
5724
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005725/**
5726 * Connection is responsive if it has no events in the waitQueue that are older than the
5727 * current time.
5728 */
5729static bool isConnectionResponsive(const Connection& connection) {
5730 const nsecs_t currentTime = now();
5731 for (const DispatchEntry* entry : connection.waitQueue) {
5732 if (entry->timeoutTime < currentTime) {
5733 return false;
5734 }
5735 }
5736 return true;
5737}
5738
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005739void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005741 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005743 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744
5745 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005746 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005747 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005748 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005750 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005751 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005752 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005753 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5754 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005755 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005756 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5757 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5758 connection->inputChannel->getConnectionToken(),
5759 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5760 finishTime);
5761 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005762
5763 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005764 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005765 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005766 restartEvent =
5767 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005768 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005769 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005770 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5771 handled);
5772 } else {
5773 restartEvent = false;
5774 }
5775
5776 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005777 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005778 // contents of the wait queue to have been drained, so we need to double-check
5779 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005780 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5781 if (dispatchEntryIt != connection->waitQueue.end()) {
5782 dispatchEntry = *dispatchEntryIt;
5783 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005784 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5785 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005786 if (!connection->responsive) {
5787 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005788 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005789 // The connection was unresponsive, and now it's responsive.
5790 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005791 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005792 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005793 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005794 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005795 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005796 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005797 } else {
5798 releaseDispatchEntry(dispatchEntry);
5799 }
5800 }
5801
5802 // Start the next dispatch cycle for this connection.
5803 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804}
5805
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005806void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5807 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5808 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5809 monitorUnresponsiveCommand->pid = pid;
5810 monitorUnresponsiveCommand->reason = std::move(reason);
5811 postCommandLocked(std::move(monitorUnresponsiveCommand));
5812}
5813
5814void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5815 std::string reason) {
5816 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5817 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5818 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5819 windowUnresponsiveCommand->reason = std::move(reason);
5820 postCommandLocked(std::move(windowUnresponsiveCommand));
5821}
5822
5823void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5824 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5825 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5826 monitorResponsiveCommand->pid = pid;
5827 postCommandLocked(std::move(monitorResponsiveCommand));
5828}
5829
5830void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5831 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5832 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5833 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5834 postCommandLocked(std::move(windowResponsiveCommand));
5835}
5836
5837/**
5838 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5839 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5840 * command entry to the command queue.
5841 */
5842void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5843 std::string reason) {
5844 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5845 if (connection.monitor) {
5846 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5847 reason.c_str());
5848 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5849 if (!pid.has_value()) {
5850 ALOGE("Could not find unresponsive monitor for connection %s",
5851 connection.inputChannel->getName().c_str());
5852 return;
5853 }
5854 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5855 return;
5856 }
5857 // If not a monitor, must be a window
5858 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5859 reason.c_str());
5860 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5861}
5862
5863/**
5864 * Tell the policy that a connection has become responsive so that it can stop ANR.
5865 */
5866void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5867 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5868 if (connection.monitor) {
5869 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5870 if (!pid.has_value()) {
5871 ALOGE("Could not find responsive monitor for connection %s",
5872 connection.inputChannel->getName().c_str());
5873 return;
5874 }
5875 sendMonitorResponsiveCommandLocked(pid.value());
5876 return;
5877 }
5878 // If not a monitor, must be a window
5879 sendWindowResponsiveCommandLocked(connectionToken);
5880}
5881
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005883 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005884 KeyEntry& keyEntry, bool handled) {
5885 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005886 if (!handled) {
5887 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005888 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005889 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005890 return false;
5891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005893 // Get the fallback key state.
5894 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005895 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005896 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005897 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005898 connection->inputState.removeFallbackKey(originalKeyCode);
5899 }
5900
5901 if (handled || !dispatchEntry->hasForegroundTarget()) {
5902 // If the application handles the original key for which we previously
5903 // generated a fallback or if the window is not a foreground window,
5904 // then cancel the associated fallback key, if any.
5905 if (fallbackKeyCode != -1) {
5906 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005908 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005909 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005910 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005912 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005913 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914
5915 mLock.unlock();
5916
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005917 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919
5920 mLock.lock();
5921
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922 // Cancel the fallback key.
5923 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005925 "application handled the original non-fallback key "
5926 "or is no longer a foreground target, "
5927 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928 options.keyCode = fallbackKeyCode;
5929 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005931 connection->inputState.removeFallbackKey(originalKeyCode);
5932 }
5933 } else {
5934 // If the application did not handle a non-fallback key, first check
5935 // that we are in a good state to perform unhandled key event processing
5936 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005937 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005938 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005941 "since this is not an initial down. "
5942 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005943 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005945 return false;
5946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948 // Dispatch the unhandled key to the policy.
5949#if DEBUG_OUTBOUND_EVENT_DETAILS
5950 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005951 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005952 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005953#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005954 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955
5956 mLock.unlock();
5957
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005958 bool fallback =
5959 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005960 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005961
5962 mLock.lock();
5963
5964 if (connection->status != Connection::STATUS_NORMAL) {
5965 connection->inputState.removeFallbackKey(originalKeyCode);
5966 return false;
5967 }
5968
5969 // Latch the fallback keycode for this key on an initial down.
5970 // The fallback keycode cannot change at any other point in the lifecycle.
5971 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973 fallbackKeyCode = event.getKeyCode();
5974 } else {
5975 fallbackKeyCode = AKEYCODE_UNKNOWN;
5976 }
5977 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5978 }
5979
5980 ALOG_ASSERT(fallbackKeyCode != -1);
5981
5982 // Cancel the fallback key if the policy decides not to send it anymore.
5983 // We will continue to dispatch the key to the policy but we will no
5984 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005985 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5986 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005987#if DEBUG_OUTBOUND_EVENT_DETAILS
5988 if (fallback) {
5989 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005990 "as a fallback for %d, but on the DOWN it had requested "
5991 "to send %d instead. Fallback canceled.",
5992 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 } else {
5994 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005995 "but on the DOWN it had requested to send %d. "
5996 "Fallback canceled.",
5997 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005998 }
5999#endif
6000
6001 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6002 "canceling fallback, policy no longer desires it");
6003 options.keyCode = fallbackKeyCode;
6004 synthesizeCancelationEventsForConnectionLocked(connection, options);
6005
6006 fallback = false;
6007 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006008 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006009 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 }
6011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012
6013#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006014 {
6015 std::string msg;
6016 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6017 connection->inputState.getFallbackKeys();
6018 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006019 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006021 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006022 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006023 }
6024#endif
6025
6026 if (fallback) {
6027 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006028 keyEntry.eventTime = event.getEventTime();
6029 keyEntry.deviceId = event.getDeviceId();
6030 keyEntry.source = event.getSource();
6031 keyEntry.displayId = event.getDisplayId();
6032 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6033 keyEntry.keyCode = fallbackKeyCode;
6034 keyEntry.scanCode = event.getScanCode();
6035 keyEntry.metaState = event.getMetaState();
6036 keyEntry.repeatCount = event.getRepeatCount();
6037 keyEntry.downTime = event.getDownTime();
6038 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006039
6040#if DEBUG_OUTBOUND_EVENT_DETAILS
6041 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006042 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006043 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044#endif
6045 return true; // restart the event
6046 } else {
6047#if DEBUG_OUTBOUND_EVENT_DETAILS
6048 ALOGD("Unhandled key event: No fallback key.");
6049#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006050
6051 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 }
6054 }
6055 return false;
6056}
6057
6058bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006059 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006060 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 return false;
6062}
6063
6064void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6065 mLock.unlock();
6066
Sean Stoutb4e0a592021-02-23 07:34:53 -08006067 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6068 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069
6070 mLock.lock();
6071}
6072
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073void InputDispatcher::traceInboundQueueLengthLocked() {
6074 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006075 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 }
6077}
6078
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006079void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080 if (ATRACE_ENABLED()) {
6081 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006082 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6083 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084 }
6085}
6086
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006087void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 if (ATRACE_ENABLED()) {
6089 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006090 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6091 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 }
6093}
6094
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006095void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006096 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006098 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 dumpDispatchStateLocked(dump);
6100
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006101 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006102 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006103 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006104 }
6105}
6106
6107void InputDispatcher::monitor() {
6108 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006109 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006110 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006111 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112}
6113
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006114/**
6115 * Wake up the dispatcher and wait until it processes all events and commands.
6116 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6117 * this method can be safely called from any thread, as long as you've ensured that
6118 * the work you are interested in completing has already been queued.
6119 */
6120bool InputDispatcher::waitForIdle() {
6121 /**
6122 * Timeout should represent the longest possible time that a device might spend processing
6123 * events and commands.
6124 */
6125 constexpr std::chrono::duration TIMEOUT = 100ms;
6126 std::unique_lock lock(mLock);
6127 mLooper->wake();
6128 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6129 return result == std::cv_status::no_timeout;
6130}
6131
Vishnu Naire798b472020-07-23 13:52:21 -07006132/**
6133 * Sets focus to the window identified by the token. This must be called
6134 * after updating any input window handles.
6135 *
6136 * Params:
6137 * request.token - input channel token used to identify the window that should gain focus.
6138 * request.focusedToken - the token that the caller expects currently to be focused. If the
6139 * specified token does not match the currently focused window, this request will be dropped.
6140 * If the specified focused token matches the currently focused window, the call will succeed.
6141 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6142 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6143 * when requesting the focus change. This determines which request gets
6144 * precedence if there is a focus change request from another source such as pointer down.
6145 */
Vishnu Nair958da932020-08-21 17:12:37 -07006146void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6147 { // acquire lock
6148 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006149 std::optional<FocusResolver::FocusChanges> changes =
6150 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6151 if (changes) {
6152 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006153 }
6154 } // release lock
6155 // Wake up poll loop since it may need to make new input dispatching choices.
6156 mLooper->wake();
6157}
6158
Vishnu Nairc519ff72021-01-21 08:23:08 -08006159void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6160 if (changes.oldFocus) {
6161 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006162 if (focusedInputChannel) {
6163 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6164 "focus left window");
6165 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006166 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006167 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006168 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006169 if (changes.newFocus) {
6170 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006171 }
6172
Prabir Pradhan99987712020-11-10 18:43:05 -08006173 // If a window has pointer capture, then it must have focus. We need to ensure that this
6174 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6175 // If the window loses focus before it loses pointer capture, then the window can be in a state
6176 // where it has pointer capture but not focus, violating the contract. Therefore we must
6177 // dispatch the pointer capture event before the focus event. Since focus events are added to
6178 // the front of the queue (above), we add the pointer capture event to the front of the queue
6179 // after the focus events are added. This ensures the pointer capture event ends up at the
6180 // front.
6181 disablePointerCaptureForcedLocked();
6182
Vishnu Nairc519ff72021-01-21 08:23:08 -08006183 if (mFocusedDisplayId == changes.displayId) {
6184 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006185 }
6186}
Vishnu Nair958da932020-08-21 17:12:37 -07006187
Prabir Pradhan99987712020-11-10 18:43:05 -08006188void InputDispatcher::disablePointerCaptureForcedLocked() {
6189 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6190 return;
6191 }
6192
6193 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6194
6195 if (mFocusedWindowRequestedPointerCapture) {
6196 mFocusedWindowRequestedPointerCapture = false;
6197 setPointerCaptureLocked(false);
6198 }
6199
6200 if (!mWindowTokenWithPointerCapture) {
6201 // No need to send capture changes because no window has capture.
6202 return;
6203 }
6204
6205 if (mPendingEvent != nullptr) {
6206 // Move the pending event to the front of the queue. This will give the chance
6207 // for the pending event to be dropped if it is a captured event.
6208 mInboundQueue.push_front(mPendingEvent);
6209 mPendingEvent = nullptr;
6210 }
6211
6212 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6213 false /* hasCapture */);
6214 mInboundQueue.push_front(std::move(entry));
6215}
6216
Prabir Pradhan99987712020-11-10 18:43:05 -08006217void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6218 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6219 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6220 commandEntry->enabled = enabled;
6221 postCommandLocked(std::move(commandEntry));
6222}
6223
6224void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6225 android::inputdispatcher::CommandEntry* commandEntry) {
6226 mLock.unlock();
6227
6228 mPolicy->setPointerCapture(commandEntry->enabled);
6229
6230 mLock.lock();
6231}
6232
Vishnu Nair599f1412021-06-21 10:39:58 -07006233void InputDispatcher::displayRemoved(int32_t displayId) {
6234 { // acquire lock
6235 std::scoped_lock _l(mLock);
6236 // Set an empty list to remove all handles from the specific display.
6237 setInputWindowsLocked(/* window handles */ {}, displayId);
6238 setFocusedApplicationLocked(displayId, nullptr);
6239 // Call focus resolver to clean up stale requests. This must be called after input windows
6240 // have been removed for the removed display.
6241 mFocusResolver.displayRemoved(displayId);
6242 } // release lock
6243
6244 // Wake up poll loop since it may need to make new input dispatching choices.
6245 mLooper->wake();
6246}
6247
chaviw15fab6f2021-06-07 14:15:52 -05006248void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6249 // The listener sends the windows as a flattened array. Separate the windows by display for
6250 // more convenient parsing.
6251 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6252
6253 for (const auto& info : windowInfos) {
6254 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6255 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6256 }
6257 setInputWindows(handlesPerDisplay);
6258}
6259
Garfield Tane84e6f92019-08-29 17:28:41 -07006260} // namespace android::inputdispatcher