blob: d32d6f424671dbe64d36da049bd896c482a4606f [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
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 synthesizeCancelationEventsForAllConnectionsLocked(options);
1275 return true;
1276}
1277
Vishnu Nairad321cd2020-08-20 16:40:21 -07001278void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001279 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001280 if (mPendingEvent != nullptr) {
1281 // Move the pending event to the front of the queue. This will give the chance
1282 // for the pending event to get dispatched to the newly focused window
1283 mInboundQueue.push_front(mPendingEvent);
1284 mPendingEvent = nullptr;
1285 }
1286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 std::unique_ptr<FocusEntry> focusEntry =
1288 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1289 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001290
1291 // This event should go to the front of the queue, but behind all other focus events
1292 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001293 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001294 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 [](const std::shared_ptr<EventEntry>& event) {
1296 return event->type == EventEntry::Type::FOCUS;
1297 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001298
1299 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001301}
1302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001304 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001305 if (channel == nullptr) {
1306 return; // Window has gone away
1307 }
1308 InputTarget target;
1309 target.inputChannel = channel;
1310 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1311 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001312 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1313 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001314 std::string reason = std::string("reason=").append(entry->reason);
1315 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001316 dispatchEventLocked(currentTime, entry, {target});
1317}
1318
Prabir Pradhan99987712020-11-10 18:43:05 -08001319void InputDispatcher::dispatchPointerCaptureChangedLocked(
1320 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1321 DropReason& dropReason) {
1322 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001323 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1324 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1325 }
1326 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001327 // Pointer capture was already forcefully disabled because of focus change.
1328 dropReason = DropReason::NOT_DROPPED;
1329 return;
1330 }
1331
1332 // Set drop reason for early returns
1333 dropReason = DropReason::NO_POINTER_CAPTURE;
1334
1335 sp<IBinder> token;
1336 if (entry->pointerCaptureEnabled) {
1337 // Enable Pointer Capture
1338 if (!mFocusedWindowRequestedPointerCapture) {
1339 // This can happen if a window requests capture and immediately releases capture.
1340 ALOGW("No window requested Pointer Capture.");
1341 return;
1342 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001343 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001344 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1345 mWindowTokenWithPointerCapture = token;
1346 } else {
1347 // Disable Pointer Capture
1348 token = mWindowTokenWithPointerCapture;
1349 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001350 if (mFocusedWindowRequestedPointerCapture) {
1351 mFocusedWindowRequestedPointerCapture = false;
1352 setPointerCaptureLocked(false);
1353 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001354 }
1355
1356 auto channel = getInputChannelLocked(token);
1357 if (channel == nullptr) {
1358 // Window has gone away, clean up Pointer Capture state.
1359 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001360 if (mFocusedWindowRequestedPointerCapture) {
1361 mFocusedWindowRequestedPointerCapture = false;
1362 setPointerCaptureLocked(false);
1363 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001364 return;
1365 }
1366 InputTarget target;
1367 target.inputChannel = channel;
1368 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1369 entry->dispatchInProgress = true;
1370 dispatchEventLocked(currentTime, entry, {target});
1371
1372 dropReason = DropReason::NOT_DROPPED;
1373}
1374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001375bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001376 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001378 if (!entry->dispatchInProgress) {
1379 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1380 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1381 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1382 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001383 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 // We have seen two identical key downs in a row which indicates that the device
1385 // driver is automatically generating key repeats itself. We take note of the
1386 // repeat here, but we disable our own next key repeat timer since it is clear that
1387 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001388 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1389 // Make sure we don't get key down from a different device. If a different
1390 // device Id has same key pressed down, the new device Id will replace the
1391 // current one to hold the key repeat with repeat count reset.
1392 // In the future when got a KEY_UP on the device id, drop it and do not
1393 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1395 resetKeyRepeatLocked();
1396 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1397 } else {
1398 // Not a repeat. Save key down state in case we do see a repeat later.
1399 resetKeyRepeatLocked();
1400 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1401 }
1402 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001403 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1404 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001405 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001406#if DEBUG_INBOUND_EVENT_DETAILS
1407 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1408#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 resetKeyRepeatLocked();
1411 }
1412
1413 if (entry->repeatCount == 1) {
1414 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1415 } else {
1416 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1417 }
1418
1419 entry->dispatchInProgress = true;
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 }
1423
1424 // Handle case where the policy asked us to try again later last time.
1425 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1426 if (currentTime < entry->interceptKeyWakeupTime) {
1427 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1428 *nextWakeupTime = entry->interceptKeyWakeupTime;
1429 }
1430 return false; // wait until next wakeup
1431 }
1432 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1433 entry->interceptKeyWakeupTime = 0;
1434 }
1435
1436 // Give the policy a chance to intercept the key.
1437 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1438 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001439 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001440 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001441 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001442 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001443 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001445 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 return false; // wait for the command to run
1447 } else {
1448 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1449 }
1450 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001451 if (*dropReason == DropReason::NOT_DROPPED) {
1452 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454 }
1455
1456 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001457 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001458 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001459 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1460 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001461 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 return true;
1463 }
1464
1465 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001466 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001469 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 return false;
1471 }
1472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return true;
1476 }
1477
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001478 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
1481 // Dispatch the key.
1482 dispatchEventLocked(currentTime, entry, inputTargets);
1483 return true;
1484}
1485
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001486void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001488 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001489 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1490 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001491 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1492 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1493 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494#endif
1495}
1496
Chris Yef59a2f42020-10-16 12:55:26 -07001497void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1498 mLock.unlock();
1499
1500 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1501 if (entry->accuracyChanged) {
1502 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1503 }
1504 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1505 entry->hwTimestamp, entry->values);
1506 mLock.lock();
1507}
1508
1509void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1510 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1511#if DEBUG_OUTBOUND_EVENT_DETAILS
1512 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1513 "source=0x%x, sensorType=%s",
1514 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001515 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001516#endif
1517 std::unique_ptr<CommandEntry> commandEntry =
1518 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1519 commandEntry->sensorEntry = entry;
1520 postCommandLocked(std::move(commandEntry));
1521}
1522
1523bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1524#if DEBUG_OUTBOUND_EVENT_DETAILS
1525 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1526 NamedEnum::string(sensorType).c_str());
1527#endif
1528 { // acquire lock
1529 std::scoped_lock _l(mLock);
1530
1531 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1532 std::shared_ptr<EventEntry> entry = *it;
1533 if (entry->type == EventEntry::Type::SENSOR) {
1534 it = mInboundQueue.erase(it);
1535 releaseInboundEventLocked(entry);
1536 }
1537 }
1538 }
1539 return true;
1540}
1541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001542bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001543 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001544 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001546 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 entry->dispatchInProgress = true;
1548
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551
1552 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001553 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1556 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return true;
1558 }
1559
1560 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1561
1562 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001563 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564
1565 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 if (isPointerEvent) {
1568 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001570 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001571 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 } else {
1573 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001574 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 return false;
1579 }
1580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001583 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1584 return true;
1585 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001587 CancelationOptions::Mode mode(isPointerEvent
1588 ? CancelationOptions::CANCEL_POINTER_EVENTS
1589 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1590 CancelationOptions options(mode, "input event injection failed");
1591 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 return true;
1593 }
1594
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001595 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001596 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001598 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001599 std::unordered_map<int32_t, TouchState>::iterator it =
1600 mTouchStatesByDisplay.find(entry->displayId);
1601 if (it != mTouchStatesByDisplay.end()) {
1602 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001603 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001604 // The event has gone through these portal windows, so we add monitoring targets of
1605 // the corresponding displays as well.
1606 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05001607 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001608 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001609 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001610 }
1611 }
1612 }
1613 }
1614
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 // Dispatch the motion.
1616 if (conflictingPointerActions) {
1617 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 synthesizeCancelationEventsForAllConnectionsLocked(options);
1620 }
1621 dispatchEventLocked(currentTime, entry, inputTargets);
1622 return true;
1623}
1624
chaviw3277faf2021-05-19 16:45:23 -05001625void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001626 bool isExiting, const MotionEntry& motionEntry) {
1627 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1628 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1629 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1630 PointerCoords pointerCoords;
1631 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1632 pointerCoords.transform(windowHandle->getInfo()->transform);
1633
1634 std::unique_ptr<DragEntry> dragEntry =
1635 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1636 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1637 pointerCoords.getY());
1638
1639 enqueueInboundEventLocked(std::move(dragEntry));
1640}
1641
1642void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1643 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1644 if (channel == nullptr) {
1645 return; // Window has gone away
1646 }
1647 InputTarget target;
1648 target.inputChannel = channel;
1649 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1650 entry->dispatchInProgress = true;
1651 dispatchEventLocked(currentTime, entry, {target});
1652}
1653
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001656 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 ", policyFlags=0x%x, "
1658 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1659 "metaState=0x%x, buttonState=0x%x,"
1660 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001661 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1662 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1663 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001665 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001667 "x=%f, y=%f, pressure=%f, size=%f, "
1668 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1669 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1671 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1672 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1673 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1674 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1675 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1676 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1677 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1678 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1679 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 }
1681#endif
1682}
1683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001684void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1685 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001686 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001687 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688#if DEBUG_DISPATCH_CYCLE
1689 ALOGD("dispatchEventToCurrentInputTargets");
1690#endif
1691
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001692 updateInteractionTokensLocked(*eventEntry, inputTargets);
1693
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001698 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001699 sp<Connection> connection =
1700 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001701 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001702 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001704 if (DEBUG_FOCUS) {
1705 ALOGD("Dropping event delivery to target with channel '%s' because it "
1706 "is no longer registered with the input dispatcher.",
1707 inputTarget.inputChannel->getName().c_str());
1708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 }
1710 }
1711}
1712
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001713void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1714 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1715 // If the policy decides to close the app, we will get a channel removal event via
1716 // unregisterInputChannel, and will clean up the connection that way. We are already not
1717 // sending new pointers to the connection when it blocked, but focused events will continue to
1718 // pile up.
1719 ALOGW("Canceling events for %s because it is unresponsive",
1720 connection->inputChannel->getName().c_str());
1721 if (connection->status == Connection::STATUS_NORMAL) {
1722 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1723 "application not responding");
1724 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
1726}
1727
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001728void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001729 if (DEBUG_FOCUS) {
1730 ALOGD("Resetting ANR timeouts.");
1731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732
1733 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001734 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001735 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736}
1737
Tiger Huang721e26f2018-07-24 22:26:19 +08001738/**
1739 * Get the display id that the given event should go to. If this event specifies a valid display id,
1740 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1741 * Focused display is the display that the user most recently interacted with.
1742 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001743int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001744 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001745 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001746 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001747 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1748 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 break;
1750 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001751 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001752 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1753 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 break;
1755 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001756 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001757 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001758 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001759 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001760 case EventEntry::Type::SENSOR:
1761 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001762 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001763 return ADISPLAY_ID_NONE;
1764 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001765 }
1766 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1767}
1768
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001769bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1770 const char* focusedWindowName) {
1771 if (mAnrTracker.empty()) {
1772 // already processed all events that we waited for
1773 mKeyIsWaitingForEventsTimeout = std::nullopt;
1774 return false;
1775 }
1776
1777 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1778 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001779 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001780 mKeyIsWaitingForEventsTimeout = currentTime +
1781 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1782 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001783 return true;
1784 }
1785
1786 // We still have pending events, and already started the timer
1787 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1788 return true; // Still waiting
1789 }
1790
1791 // Waited too long, and some connection still hasn't processed all motions
1792 // Just send the key to the focused window
1793 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1794 focusedWindowName);
1795 mKeyIsWaitingForEventsTimeout = std::nullopt;
1796 return false;
1797}
1798
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001799InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1800 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1801 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001802 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803
Tiger Huang721e26f2018-07-24 22:26:19 +08001804 int32_t displayId = getTargetDisplayId(entry);
chaviw3277faf2021-05-19 16:45:23 -05001805 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001806 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001807 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1808
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 // If there is no currently focused window and no focused application
1810 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001811 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1812 ALOGI("Dropping %s event because there is no focused window or focused application in "
1813 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001814 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
1817
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1819 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1820 // start interacting with another application via touch (app switch). This code can be removed
1821 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1822 // an app is expected to have a focused window.
1823 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1824 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1825 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001826 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1827 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1828 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001830 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831 ALOGW("Waiting because no window has focus but %s may eventually add a "
1832 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001833 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001834 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1837 // Already raised ANR. Drop the event
1838 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001839 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 } else {
1842 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001844 }
1845 }
1846
1847 // we have a valid, non-null focused window
1848 resetNoFocusedWindowTimeoutLocked();
1849
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
1854
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001855 if (focusedWindowHandle->getInfo()->paused) {
1856 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001858 }
1859
1860 // If the event is a key event, then we must wait for all previous events to
1861 // complete before delivering it because previous events may have the
1862 // side-effect of transferring focus to a different window and we want to
1863 // ensure that the following keys are sent to the new window.
1864 //
1865 // Suppose the user touches a button in a window then immediately presses "A".
1866 // If the button causes a pop-up window to appear then we want to ensure that
1867 // the "A" key is delivered to the new pop-up window. This is because users
1868 // often anticipate pending UI changes when typing on a keyboard.
1869 // To obtain this behavior, we must serialize key events with respect to all
1870 // prior input events.
1871 if (entry.type == EventEntry::Type::KEY) {
1872 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1873 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
1877
1878 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001879 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1881 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882
1883 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885}
1886
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887/**
1888 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1889 * that are currently unresponsive.
1890 */
1891std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1892 const std::vector<TouchedMonitor>& monitors) const {
1893 std::vector<TouchedMonitor> responsiveMonitors;
1894 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1895 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1896 sp<Connection> connection = getConnectionLocked(
1897 monitor.monitor.inputChannel->getConnectionToken());
1898 if (connection == nullptr) {
1899 ALOGE("Could not find connection for monitor %s",
1900 monitor.monitor.inputChannel->getName().c_str());
1901 return false;
1902 }
1903 if (!connection->responsive) {
1904 ALOGW("Unresponsive monitor %s will not get the new gesture",
1905 connection->inputChannel->getName().c_str());
1906 return false;
1907 }
1908 return true;
1909 });
1910 return responsiveMonitors;
1911}
1912
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001913InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1914 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1915 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 enum InjectionPermission {
1918 INJECTION_PERMISSION_UNKNOWN,
1919 INJECTION_PERMISSION_GRANTED,
1920 INJECTION_PERMISSION_DENIED
1921 };
1922
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 // For security reasons, we defer updating the touch state until we are sure that
1924 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001925 int32_t displayId = entry.displayId;
1926 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1928
1929 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001930 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw3277faf2021-05-19 16:45:23 -05001932 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1933 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001935 // Copy current touch state into tempTouchState.
1936 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1937 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001938 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001940 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1941 mTouchStatesByDisplay.find(displayId);
1942 if (oldStateIt != mTouchStatesByDisplay.end()) {
1943 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001945 }
1946
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 bool isSplit = tempTouchState.split;
1948 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1949 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1950 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001951 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1952 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1953 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1954 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1955 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001956 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 bool wrongDevice = false;
1958 if (newGesture) {
1959 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001960 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001961 ALOGI("Dropping event because a pointer for a different device is already down "
1962 "in display %" PRId32,
1963 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001964 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 switchedDevice = false;
1967 wrongDevice = true;
1968 goto Failed;
1969 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001970 tempTouchState.reset();
1971 tempTouchState.down = down;
1972 tempTouchState.deviceId = entry.deviceId;
1973 tempTouchState.source = entry.source;
1974 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001976 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001977 ALOGI("Dropping move event because a pointer for a different device is already active "
1978 "in display %" PRId32,
1979 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001980 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001981 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001982 switchedDevice = false;
1983 wrongDevice = true;
1984 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
1986
1987 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1988 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1989
Garfield Tan00f511d2019-06-12 16:55:40 -07001990 int32_t x;
1991 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001993 // Always dispatch mouse events to cursor position.
1994 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001995 x = int32_t(entry.xCursorPosition);
1996 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001997 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001998 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1999 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002000 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002001 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07002002 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2004 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002005
2006 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002007 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002008 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002011 if (newTouchedWindowHandle != nullptr &&
2012 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002013 // New window supports splitting, but we should never split mouse events.
2014 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 } else if (isSplit) {
2016 // New window does not support splitting but we have already split events.
2017 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002018 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
2020
2021 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002022 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002024 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002025 }
2026
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2028 ALOGI("Not sending touch event to %s because it is paused",
2029 newTouchedWindowHandle->getName().c_str());
2030 newTouchedWindowHandle = nullptr;
2031 }
2032
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002033 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002034 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002035 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2036 if (!isResponsive) {
2037 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2039 newTouchedWindowHandle = nullptr;
2040 }
2041 }
2042
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002043 // Drop events that can't be trusted due to occlusion
2044 if (newTouchedWindowHandle != nullptr &&
2045 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2046 TouchOcclusionInfo occlusionInfo =
2047 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002048 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002049 if (DEBUG_TOUCH_OCCLUSION) {
2050 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2051 for (const auto& log : occlusionInfo.debugInfo) {
2052 ALOGD("%s", log.c_str());
2053 }
2054 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002055 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2056 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2057 ALOGW("Dropping untrusted touch event due to %s/%d",
2058 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2059 newTouchedWindowHandle = nullptr;
2060 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002061 }
2062 }
2063
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064 // Also don't send the new touch event to unresponsive gesture monitors
2065 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2066
Michael Wright3dd60e22019-03-27 22:06:44 +00002067 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2068 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 "(%d, %d) in display %" PRId32 ".",
2070 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002071 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 goto Failed;
2073 }
2074
2075 if (newTouchedWindowHandle != nullptr) {
2076 // Set target flags.
2077 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2078 if (isSplit) {
2079 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2082 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2083 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2084 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2085 }
2086
2087 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002088 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2089 newHoverWindowHandle = nullptr;
2090 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002091 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002092 }
2093
2094 // Update the temporary touch state.
2095 BitSet32 pointerIds;
2096 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002097 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002098 pointerIds.markBit(pointerId);
2099 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002103 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 } else {
2105 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2106
2107 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002108 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002109 if (DEBUG_FOCUS) {
2110 ALOGD("Dropping event because the pointer is not down or we previously "
2111 "dropped the pointer down event in display %" PRId32,
2112 displayId);
2113 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002114 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 goto Failed;
2116 }
2117
arthurhung6d4bed92021-03-17 11:59:33 +08002118 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002119
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002121 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2124 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
chaviw3277faf2021-05-19 16:45:23 -05002126 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002128 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002129 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2130 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002131 if (DEBUG_FOCUS) {
2132 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2133 oldTouchedWindowHandle->getName().c_str(),
2134 newTouchedWindowHandle->getName().c_str(), displayId);
2135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002137 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2138 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2139 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
2141 // Make a slippery entrance into the new window.
2142 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2143 isSplit = true;
2144 }
2145
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002146 int32_t targetFlags =
2147 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 if (isSplit) {
2149 targetFlags |= InputTarget::FLAG_SPLIT;
2150 }
2151 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2152 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002153 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2154 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156
2157 BitSet32 pointerIds;
2158 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002161 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
2163 }
2164 }
2165
2166 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002167 // Let the previous window know that the hover sequence is over, unless we already did it
2168 // when dispatching it as is to newTouchedWindowHandle.
2169 if (mLastHoverWindowHandle != nullptr &&
2170 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2171 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172#if DEBUG_HOVER
2173 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2177 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 }
2179
Garfield Tandf26e862020-07-01 20:18:19 -07002180 // Let the new window know that the hover sequence is starting, unless we already did it
2181 // when dispatching it as is to newTouchedWindowHandle.
2182 if (newHoverWindowHandle != nullptr &&
2183 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2184 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185#if DEBUG_HOVER
2186 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002187 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2190 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2191 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
2193 }
2194
2195 // Check permission to inject into all touched foreground windows and ensure there
2196 // is at least one touched foreground window.
2197 {
2198 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002199 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2201 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002202 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002203 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 injectionPermission = INJECTION_PERMISSION_DENIED;
2205 goto Failed;
2206 }
2207 }
2208 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002209 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002210 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002211 ALOGI("Dropping event because there is no touched foreground window in display "
2212 "%" PRId32 " or gesture monitor to receive it.",
2213 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002214 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 goto Failed;
2216 }
2217
2218 // Permission granted to injection into all touched foreground windows.
2219 injectionPermission = INJECTION_PERMISSION_GRANTED;
2220 }
2221
2222 // Check whether windows listening for outside touches are owned by the same UID. If it is
2223 // set the policy flag that we will not reveal coordinate information to this window.
2224 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002225 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002226 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002227 if (foregroundWindowHandle) {
2228 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw3277faf2021-05-19 16:45:23 -05002231 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2232 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2233 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002234 InputTarget::FLAG_ZERO_COORDS,
2235 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
2238 }
2239 }
2240 }
2241
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // If this is the first pointer going down and the touched window has a wallpaper
2243 // then also add the touched wallpaper windows so they are locked in for the duration
2244 // of the touch gesture.
2245 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2246 // engine only supports touch events. We would need to add a mechanism similar
2247 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2248 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002249 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002251 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw3277faf2021-05-19 16:45:23 -05002252 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002253 getWindowHandlesLocked(displayId);
chaviw3277faf2021-05-19 16:45:23 -05002254 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2255 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 if (info->displayId == displayId &&
chaviw3277faf2021-05-19 16:45:23 -05002257 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002258 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 .addOrUpdateWindow(windowHandle,
2260 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2261 InputTarget::
2262 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2263 InputTarget::FLAG_DISPATCH_AS_IS,
2264 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266 }
2267 }
2268 }
2269
2270 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002271 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002273 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002279 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002281 }
2282
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 // Drop the outside or hover touch windows since we will not care about them
2284 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002285 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287Failed:
2288 // Check injection permission once and for all.
2289 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002290 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 injectionPermission = INJECTION_PERMISSION_GRANTED;
2292 } else {
2293 injectionPermission = INJECTION_PERMISSION_DENIED;
2294 }
2295 }
2296
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002297 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2298 return injectionResult;
2299 }
2300
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002302 if (!wrongDevice) {
2303 if (switchedDevice) {
2304 if (DEBUG_FOCUS) {
2305 ALOGD("Conflicting pointer actions: Switched to a different device.");
2306 }
2307 *outConflictingPointerActions = true;
2308 }
2309
2310 if (isHoverAction) {
2311 // Started hovering, therefore no longer down.
2312 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002313 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002314 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2315 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 *outConflictingPointerActions = true;
2318 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002319 tempTouchState.reset();
2320 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2321 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2322 tempTouchState.deviceId = entry.deviceId;
2323 tempTouchState.source = entry.source;
2324 tempTouchState.displayId = displayId;
2325 }
2326 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2327 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2328 // All pointers up or canceled.
2329 tempTouchState.reset();
2330 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2331 // First pointer went down.
2332 if (oldState && oldState->down) {
2333 if (DEBUG_FOCUS) {
2334 ALOGD("Conflicting pointer actions: Down received while already down.");
2335 }
2336 *outConflictingPointerActions = true;
2337 }
2338 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2339 // One pointer went up.
2340 if (isSplit) {
2341 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2342 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002344 for (size_t i = 0; i < tempTouchState.windows.size();) {
2345 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2346 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2347 touchedWindow.pointerIds.clearBit(pointerId);
2348 if (touchedWindow.pointerIds.isEmpty()) {
2349 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2350 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002353 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002355 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002356 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002357
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 // Save changes unless the action was scroll in which case the temporary touch
2359 // state was only valid for this one action.
2360 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2361 if (tempTouchState.displayId >= 0) {
2362 mTouchStatesByDisplay[displayId] = tempTouchState;
2363 } else {
2364 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002368 // Update hover state.
2369 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 return injectionResult;
2373}
2374
arthurhung6d4bed92021-03-17 11:59:33 +08002375void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw3277faf2021-05-19 16:45:23 -05002376 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002377 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2378 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2379 true /*ignoreDragWindow*/);
2380 if (dropWindow) {
2381 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2382 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002383 } else {
2384 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002385 }
2386 mDragState.reset();
2387}
2388
2389void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2390 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002391 return;
2392 }
2393
arthurhung6d4bed92021-03-17 11:59:33 +08002394 if (!mDragState->isStartDrag) {
2395 mDragState->isStartDrag = true;
2396 mDragState->isStylusButtonDownAtStart =
2397 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2398 }
2399
arthurhungb89ccb02020-12-30 16:19:01 +08002400 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2401 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2402 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2403 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002404 // Handle the special case : stylus button no longer pressed.
2405 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2406 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2407 finishDragAndDrop(entry.displayId, x, y);
2408 return;
2409 }
2410
chaviw3277faf2021-05-19 16:45:23 -05002411 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002412 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002413 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2414 true /*ignoreDragWindow*/);
2415 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002416 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2417 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2418 if (mDragState->dragHoverWindowHandle != nullptr) {
2419 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2420 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002421 }
arthurhung6d4bed92021-03-17 11:59:33 +08002422 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002423 }
2424 // enqueue drag location if needed.
2425 if (hoverWindowHandle != nullptr) {
2426 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2427 }
arthurhung6d4bed92021-03-17 11:59:33 +08002428 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2429 finishDragAndDrop(entry.displayId, x, y);
2430 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002431 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002432 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002433 }
2434}
2435
chaviw3277faf2021-05-19 16:45:23 -05002436void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002437 int32_t targetFlags, BitSet32 pointerIds,
2438 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439 std::vector<InputTarget>::iterator it =
2440 std::find_if(inputTargets.begin(), inputTargets.end(),
2441 [&windowHandle](const InputTarget& inputTarget) {
2442 return inputTarget.inputChannel->getConnectionToken() ==
2443 windowHandle->getToken();
2444 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002445
chaviw3277faf2021-05-19 16:45:23 -05002446 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002447
2448 if (it == inputTargets.end()) {
2449 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002450 std::shared_ptr<InputChannel> inputChannel =
2451 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002452 if (inputChannel == nullptr) {
2453 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2454 return;
2455 }
2456 inputTarget.inputChannel = inputChannel;
2457 inputTarget.flags = targetFlags;
2458 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002459 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002460 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002461 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002462 inputTargets.push_back(inputTarget);
2463 it = inputTargets.end() - 1;
2464 }
2465
2466 ALOG_ASSERT(it->flags == targetFlags);
2467 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2468
chaviw1ff3d1e2020-07-01 15:53:47 -07002469 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470}
2471
Michael Wright3dd60e22019-03-27 22:06:44 +00002472void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 int32_t displayId, float xOffset,
2474 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002475 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2476 mGlobalMonitorsByDisplay.find(displayId);
2477
2478 if (it != mGlobalMonitorsByDisplay.end()) {
2479 const std::vector<Monitor>& monitors = it->second;
2480 for (const Monitor& monitor : monitors) {
2481 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484}
2485
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2487 float yOffset,
2488 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002489 InputTarget target;
2490 target.inputChannel = monitor.inputChannel;
2491 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002492 ui::Transform t;
2493 t.set(xOffset, yOffset);
2494 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002495 inputTargets.push_back(target);
2496}
2497
chaviw3277faf2021-05-19 16:45:23 -05002498bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499 const InjectionState* injectionState) {
2500 if (injectionState &&
2501 (windowHandle == nullptr ||
2502 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2503 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002504 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 "owned by uid %d",
2507 injectionState->injectorPid, injectionState->injectorUid,
2508 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 } else {
2510 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
2513 return false;
2514 }
2515 return true;
2516}
2517
Robert Carrc9bf1d32020-04-13 17:21:08 -07002518/**
2519 * Indicate whether one window handle should be considered as obscuring
2520 * another window handle. We only check a few preconditions. Actually
2521 * checking the bounds is left to the caller.
2522 */
chaviw3277faf2021-05-19 16:45:23 -05002523static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2524 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002525 // Compare by token so cloned layers aren't counted
2526 if (haveSameToken(windowHandle, otherHandle)) {
2527 return false;
2528 }
2529 auto info = windowHandle->getInfo();
2530 auto otherInfo = otherHandle->getInfo();
2531 if (!otherInfo->visible) {
2532 return false;
chaviw3277faf2021-05-19 16:45:23 -05002533 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002534 // Those act as if they were invisible, so we don't need to flag them.
2535 // We do want to potentially flag touchable windows even if they have 0
2536 // opacity, since they can consume touches and alter the effects of the
2537 // user interaction (eg. apps that rely on
2538 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2539 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2540 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002541 } else if (info->ownerUid == otherInfo->ownerUid) {
2542 // If ownerUid is the same we don't generate occlusion events as there
2543 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002544 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002545 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002546 return false;
2547 } else if (otherInfo->displayId != info->displayId) {
2548 return false;
2549 }
2550 return true;
2551}
2552
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002553/**
2554 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2555 * untrusted, one should check:
2556 *
2557 * 1. If result.hasBlockingOcclusion is true.
2558 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2559 * BLOCK_UNTRUSTED.
2560 *
2561 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2562 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2563 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2564 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2565 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2566 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2567 *
2568 * If neither of those is true, then it means the touch can be allowed.
2569 */
2570InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw3277faf2021-05-19 16:45:23 -05002571 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2572 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002573 int32_t displayId = windowInfo->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002574 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002575 TouchOcclusionInfo info;
2576 info.hasBlockingOcclusion = false;
2577 info.obscuringOpacity = 0;
2578 info.obscuringUid = -1;
2579 std::map<int32_t, float> opacityByUid;
chaviw3277faf2021-05-19 16:45:23 -05002580 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002581 if (windowHandle == otherHandle) {
2582 break; // All future windows are below us. Exit early.
2583 }
chaviw3277faf2021-05-19 16:45:23 -05002584 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002585 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2586 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002587 if (DEBUG_TOUCH_OCCLUSION) {
2588 info.debugInfo.push_back(
2589 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2590 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002591 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2592 // we perform the checks below to see if the touch can be propagated or not based on the
2593 // window's touch occlusion mode
2594 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2595 info.hasBlockingOcclusion = true;
2596 info.obscuringUid = otherInfo->ownerUid;
2597 info.obscuringPackage = otherInfo->packageName;
2598 break;
2599 }
2600 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2601 uint32_t uid = otherInfo->ownerUid;
2602 float opacity =
2603 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2604 // Given windows A and B:
2605 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2606 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2607 opacityByUid[uid] = opacity;
2608 if (opacity > info.obscuringOpacity) {
2609 info.obscuringOpacity = opacity;
2610 info.obscuringUid = uid;
2611 info.obscuringPackage = otherInfo->packageName;
2612 }
2613 }
2614 }
2615 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002616 if (DEBUG_TOUCH_OCCLUSION) {
2617 info.debugInfo.push_back(
2618 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2619 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002620 return info;
2621}
2622
chaviw3277faf2021-05-19 16:45:23 -05002623std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002624 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002625 return StringPrintf(INDENT2
2626 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2627 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2628 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2629 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002630 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002631 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002632 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002633 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2634 info->frameTop, info->frameRight, info->frameBottom,
2635 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002636 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2637 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2638 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002639}
2640
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002641bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2642 if (occlusionInfo.hasBlockingOcclusion) {
2643 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2644 occlusionInfo.obscuringUid);
2645 return false;
2646 }
2647 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2648 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2649 "%.2f, maximum allowed = %.2f)",
2650 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2651 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2652 return false;
2653 }
2654 return true;
2655}
2656
chaviw3277faf2021-05-19 16:45:23 -05002657bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002660 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2661 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002662 if (windowHandle == otherHandle) {
2663 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 }
chaviw3277faf2021-05-19 16:45:23 -05002665 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002666 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002667 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 return true;
2669 }
2670 }
2671 return false;
2672}
2673
chaviw3277faf2021-05-19 16:45:23 -05002674bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002675 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002676 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2677 const WindowInfo* windowInfo = windowHandle->getInfo();
2678 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002679 if (windowHandle == otherHandle) {
2680 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002681 }
chaviw3277faf2021-05-19 16:45:23 -05002682 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002684 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002685 return true;
2686 }
2687 }
2688 return false;
2689}
2690
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002691std::string InputDispatcher::getApplicationWindowLabel(
chaviw3277faf2021-05-19 16:45:23 -05002692 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002693 if (applicationHandle != nullptr) {
2694 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002695 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 } else {
2697 return applicationHandle->getName();
2698 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002699 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002700 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002702 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 }
2704}
2705
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002706void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002707 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002708 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2709 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002710 // Focus or pointer capture changed events are passed to apps, but do not represent user
2711 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002712 return;
2713 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002714 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw3277faf2021-05-19 16:45:23 -05002715 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002716 if (focusedWindowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05002717 const WindowInfo* info = focusedWindowHandle->getInfo();
2718 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002720 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721#endif
2722 return;
2723 }
2724 }
2725
2726 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002727 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002728 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002729 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2730 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731 return;
2732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002734 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 eventType = USER_ACTIVITY_EVENT_TOUCH;
2736 }
2737 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002739 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002740 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2741 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 return;
2743 }
2744 eventType = USER_ACTIVITY_EVENT_BUTTON;
2745 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002747 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002748 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002749 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002750 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002751 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2752 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002753 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002754 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002755 break;
2756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 }
2758
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002759 std::unique_ptr<CommandEntry> commandEntry =
2760 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002761 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002763 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002764 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765}
2766
2767void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002768 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002769 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002770 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002771 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002772 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002773 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002774 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002775 ATRACE_NAME(message.c_str());
2776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777#if DEBUG_DISPATCH_CYCLE
2778 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002779 "globalScaleFactor=%f, pointerIds=0x%x %s",
2780 connection->getInputChannelName().c_str(), inputTarget.flags,
2781 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2782 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783#endif
2784
2785 // Skip this event if the connection status is not normal.
2786 // We don't want to enqueue additional outbound events if the connection is broken.
2787 if (connection->status != Connection::STATUS_NORMAL) {
2788#if DEBUG_DISPATCH_CYCLE
2789 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791#endif
2792 return;
2793 }
2794
2795 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002796 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2797 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2798 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002799 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002801 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002802 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002803 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002804 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 if (!splitMotionEntry) {
2806 return; // split event was dropped
2807 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002808 if (DEBUG_FOCUS) {
2809 ALOGD("channel '%s' ~ Split motion event.",
2810 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002811 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002812 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002813 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2814 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 return;
2816 }
2817 }
2818
2819 // Not splitting. Enqueue dispatch entries for the event as is.
2820 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2821}
2822
2823void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002825 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002826 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002827 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002829 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002830 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002831 ATRACE_NAME(message.c_str());
2832 }
2833
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002834 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835
2836 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002837 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002839 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002841 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002842 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002843 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002845 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002847 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
2850 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002851 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 startDispatchCycleLocked(currentTime, connection);
2853 }
2854}
2855
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002856void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002857 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002858 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002859 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002860 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2862 connection->getInputChannelName().c_str(),
2863 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002864 ATRACE_NAME(message.c_str());
2865 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002866 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 if (!(inputTargetFlags & dispatchMode)) {
2868 return;
2869 }
2870 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2871
2872 // This is a new event.
2873 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002874 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002875 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002877 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2878 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002879 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002881 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002882 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002883 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002884 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002885 dispatchEntry->resolvedAction = keyEntry.action;
2886 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2889 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2892 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 return; // skip the inconsistent event
2895 }
2896 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002899 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002900 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002901 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2902 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2903 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2904 static_cast<int32_t>(IdGenerator::Source::OTHER);
2905 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002906 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2907 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2908 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2909 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2910 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2911 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2912 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2913 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2914 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2915 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2916 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002917 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002918 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 }
2920 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002921 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2922 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2925 "event",
2926 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002928 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2929 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002933 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2935 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2936 }
2937 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2938 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2942 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2945 "event",
2946 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 return; // skip the inconsistent event
2949 }
2950
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002951 dispatchEntry->resolvedEventId =
2952 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2953 ? mIdGenerator.nextId()
2954 : motionEntry.id;
2955 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2956 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2957 ") to MotionEvent(id=0x%" PRIx32 ").",
2958 motionEntry.id, dispatchEntry->resolvedEventId);
2959 ATRACE_NAME(message.c_str());
2960 }
2961
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002962 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2963 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2964 // Skip reporting pointer down outside focus to the policy.
2965 break;
2966 }
2967
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002968 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002969 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970
2971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002973 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002974 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2975 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002976 break;
2977 }
Chris Yef59a2f42020-10-16 12:55:26 -07002978 case EventEntry::Type::SENSOR: {
2979 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2980 break;
2981 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002982 case EventEntry::Type::CONFIGURATION_CHANGED:
2983 case EventEntry::Type::DEVICE_RESET: {
2984 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002985 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002986 break;
2987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
2989
2990 // Remember that we are waiting for this dispatch to complete.
2991 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002992 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 }
2994
2995 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002996 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002997 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002998}
2999
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003000/**
3001 * This function is purely for debugging. It helps us understand where the user interaction
3002 * was taking place. For example, if user is touching launcher, we will see a log that user
3003 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3004 * We will see both launcher and wallpaper in that list.
3005 * Once the interaction with a particular set of connections starts, no new logs will be printed
3006 * until the set of interacted connections changes.
3007 *
3008 * The following items are skipped, to reduce the logspam:
3009 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3010 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3011 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3012 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3013 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003014 */
3015void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3016 const std::vector<InputTarget>& targets) {
3017 // Skip ACTION_UP events, and all events other than keys and motions
3018 if (entry.type == EventEntry::Type::KEY) {
3019 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3020 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3021 return;
3022 }
3023 } else if (entry.type == EventEntry::Type::MOTION) {
3024 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3025 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3026 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3027 return;
3028 }
3029 } else {
3030 return; // Not a key or a motion
3031 }
3032
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003033 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003034 std::vector<sp<Connection>> newConnections;
3035 for (const InputTarget& target : targets) {
3036 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3037 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3038 continue; // Skip windows that receive ACTION_OUTSIDE
3039 }
3040
3041 sp<IBinder> token = target.inputChannel->getConnectionToken();
3042 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003043 if (connection == nullptr) {
3044 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003045 }
3046 newConnectionTokens.insert(std::move(token));
3047 newConnections.emplace_back(connection);
3048 }
3049 if (newConnectionTokens == mInteractionConnectionTokens) {
3050 return; // no change
3051 }
3052 mInteractionConnectionTokens = newConnectionTokens;
3053
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003054 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003055 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003056 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003057 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003058 std::string message = "Interaction with: " + targetList;
3059 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003060 message += "<none>";
3061 }
3062 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3063}
3064
chaviwfd6d3512019-03-25 13:23:49 -07003065void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003066 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003067 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003068 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3069 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003070 return;
3071 }
3072
Vishnu Nairc519ff72021-01-21 08:23:08 -08003073 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003074 if (focusedToken == token) {
3075 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003076 return;
3077 }
3078
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003079 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3080 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003081 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003082 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083}
3084
3085void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003087 if (ATRACE_ENABLED()) {
3088 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003090 ATRACE_NAME(message.c_str());
3091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094#endif
3095
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003096 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3097 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003099 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003100 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003101 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
3103 // Publish the event.
3104 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3106 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003107 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3109 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003112 status = connection->inputPublisher
3113 .publishKeyEvent(dispatchEntry->seq,
3114 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3115 keyEntry.source, keyEntry.displayId,
3116 std::move(hmac), dispatchEntry->resolvedAction,
3117 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3118 keyEntry.scanCode, keyEntry.metaState,
3119 keyEntry.repeatCount, keyEntry.downTime,
3120 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
3123
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003124 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003128 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129
chaviw82357092020-01-28 13:13:06 -08003130 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3133 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003134 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003135 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3136 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003137 // Don't apply window scale here since we don't want scale to affect raw
3138 // coordinates. The scale will be sent back to the client and applied
3139 // later when requesting relative coordinates.
3140 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3141 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 }
3143 usingCoords = scaledCoords;
3144 }
3145 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146 // We don't want the dispatch target to know.
3147 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003148 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 scaledCoords[i].clear();
3150 }
3151 usingCoords = scaledCoords;
3152 }
3153 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003154
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003155 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156
3157 // Publish the motion event.
3158 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003159 .publishMotionEvent(dispatchEntry->seq,
3160 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 motionEntry.deviceId, motionEntry.source,
3162 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003163 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003166 motionEntry.edgeFlags, motionEntry.metaState,
3167 motionEntry.buttonState,
3168 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003169 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003170 motionEntry.xPrecision, motionEntry.yPrecision,
3171 motionEntry.xCursorPosition,
3172 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003173 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003174 dispatchEntry->displaySize.x,
3175 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003176 motionEntry.downTime, motionEntry.eventTime,
3177 motionEntry.pointerCount,
3178 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 break;
3180 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003181
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003182 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003183 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003184 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003185 focusEntry.id,
3186 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003187 mInTouchMode);
3188 break;
3189 }
3190
Prabir Pradhan99987712020-11-10 18:43:05 -08003191 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3192 const auto& captureEntry =
3193 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3194 status = connection->inputPublisher
3195 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3196 captureEntry.pointerCaptureEnabled);
3197 break;
3198 }
3199
arthurhungb89ccb02020-12-30 16:19:01 +08003200 case EventEntry::Type::DRAG: {
3201 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3202 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3203 dragEntry.id, dragEntry.x,
3204 dragEntry.y,
3205 dragEntry.isExiting);
3206 break;
3207 }
3208
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003209 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003210 case EventEntry::Type::DEVICE_RESET:
3211 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003212 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003213 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003214 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 }
3217
3218 // Check the result.
3219 if (status) {
3220 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003221 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 "This is unexpected because the wait queue is empty, so the pipe "
3224 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003225 "event to it, status=%s(%d)",
3226 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3227 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3229 } else {
3230 // Pipe is full and we are waiting for the app to finish process some events
3231 // before sending more events to it.
3232#if DEBUG_DISPATCH_CYCLE
3233 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 "waiting for the application to catch up",
3235 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 }
3238 } else {
3239 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003240 "status=%s(%d)",
3241 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3242 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3244 }
3245 return;
3246 }
3247
3248 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003249 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3250 connection->outboundQueue.end(),
3251 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003252 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003253 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003254 if (connection->responsive) {
3255 mAnrTracker.insert(dispatchEntry->timeoutTime,
3256 connection->inputChannel->getConnectionToken());
3257 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003258 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 }
3260}
3261
chaviw09c8d2d2020-08-24 15:48:26 -07003262std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3263 size_t size;
3264 switch (event.type) {
3265 case VerifiedInputEvent::Type::KEY: {
3266 size = sizeof(VerifiedKeyEvent);
3267 break;
3268 }
3269 case VerifiedInputEvent::Type::MOTION: {
3270 size = sizeof(VerifiedMotionEvent);
3271 break;
3272 }
3273 }
3274 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3275 return mHmacKeyManager.sign(start, size);
3276}
3277
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003278const std::array<uint8_t, 32> InputDispatcher::getSignature(
3279 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3280 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3281 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3282 // Only sign events up and down events as the purely move events
3283 // are tied to their up/down counterparts so signing would be redundant.
3284 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3285 verifiedEvent.actionMasked = actionMasked;
3286 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003287 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003288 }
3289 return INVALID_HMAC;
3290}
3291
3292const std::array<uint8_t, 32> InputDispatcher::getSignature(
3293 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3294 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3295 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3296 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003297 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003298}
3299
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003302 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303#if DEBUG_DISPATCH_CYCLE
3304 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306#endif
3307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 if (connection->status == Connection::STATUS_BROKEN ||
3309 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 return;
3311 }
3312
3313 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003314 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315}
3316
3317void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 const sp<Connection>& connection,
3319 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320#if DEBUG_DISPATCH_CYCLE
3321 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323#endif
3324
3325 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003326 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003327 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003328 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003329 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
3331 // The connection appears to be unrecoverably broken.
3332 // Ignore already broken or zombie connections.
3333 if (connection->status == Connection::STATUS_NORMAL) {
3334 connection->status = Connection::STATUS_BROKEN;
3335
3336 if (notify) {
3337 // Notify other system components.
3338 onDispatchCycleBrokenLocked(currentTime, connection);
3339 }
3340 }
3341}
3342
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003343void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3344 while (!queue.empty()) {
3345 DispatchEntry* dispatchEntry = queue.front();
3346 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003347 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 }
3349}
3350
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003351void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003353 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 }
3355 delete dispatchEntry;
3356}
3357
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003358int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3359 std::scoped_lock _l(mLock);
3360 sp<Connection> connection = getConnectionLocked(connectionToken);
3361 if (connection == nullptr) {
3362 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3363 connectionToken.get(), events);
3364 return 0; // remove the callback
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003367 bool notify;
3368 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3369 if (!(events & ALOOPER_EVENT_INPUT)) {
3370 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3371 "events=0x%x",
3372 connection->getInputChannelName().c_str(), events);
3373 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
3375
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003376 nsecs_t currentTime = now();
3377 bool gotOne = false;
3378 status_t status = OK;
3379 for (;;) {
3380 Result<InputPublisher::ConsumerResponse> result =
3381 connection->inputPublisher.receiveConsumerResponse();
3382 if (!result.ok()) {
3383 status = result.error().code();
3384 break;
3385 }
3386
3387 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3388 const InputPublisher::Finished& finish =
3389 std::get<InputPublisher::Finished>(*result);
3390 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3391 finish.consumeTime);
3392 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003393 if (shouldReportMetricsForConnection(*connection)) {
3394 const InputPublisher::Timeline& timeline =
3395 std::get<InputPublisher::Timeline>(*result);
3396 mLatencyTracker
3397 .trackGraphicsLatency(timeline.inputEventId,
3398 connection->inputChannel->getConnectionToken(),
3399 std::move(timeline.graphicsTimeline));
3400 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003401 }
3402 gotOne = true;
3403 }
3404 if (gotOne) {
3405 runCommandsLockedInterruptible();
3406 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 return 1;
3408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
3410
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003411 notify = status != DEAD_OBJECT || !connection->monitor;
3412 if (notify) {
3413 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3414 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3415 status);
3416 }
3417 } else {
3418 // Monitor channels are never explicitly unregistered.
3419 // We do it automatically when the remote endpoint is closed so don't warn about them.
3420 const bool stillHaveWindowHandle =
3421 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3422 notify = !connection->monitor && stillHaveWindowHandle;
3423 if (notify) {
3424 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3425 connection->getInputChannelName().c_str(), events);
3426 }
3427 }
3428
3429 // Remove the channel.
3430 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3431 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432}
3433
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003436 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003437 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 }
3439}
3440
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003442 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003443 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3444 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3445}
3446
3447void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3448 const CancelationOptions& options,
3449 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3450 for (const auto& it : monitorsByDisplay) {
3451 const std::vector<Monitor>& monitors = it.second;
3452 for (const Monitor& monitor : monitors) {
3453 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003454 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003455 }
3456}
3457
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003459 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003460 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003461 if (connection == nullptr) {
3462 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003464
3465 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466}
3467
3468void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3469 const sp<Connection>& connection, const CancelationOptions& options) {
3470 if (connection->status == Connection::STATUS_BROKEN) {
3471 return;
3472 }
3473
3474 nsecs_t currentTime = now();
3475
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003476 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003477 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003479 if (cancelationEvents.empty()) {
3480 return;
3481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003483 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3484 "with reality: %s, mode=%d.",
3485 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3486 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003488
3489 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003490 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003491 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3492 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003493 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003494 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003495 target.globalScaleFactor = windowInfo->globalScaleFactor;
3496 }
3497 target.inputChannel = connection->inputChannel;
3498 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3499
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003500 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003501 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003502 switch (cancelationEventEntry->type) {
3503 case EventEntry::Type::KEY: {
3504 logOutboundKeyDetails("cancel - ",
3505 static_cast<const KeyEntry&>(*cancelationEventEntry));
3506 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003508 case EventEntry::Type::MOTION: {
3509 logOutboundMotionDetails("cancel - ",
3510 static_cast<const MotionEntry&>(*cancelationEventEntry));
3511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003513 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3515 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003516 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003517 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003518 break;
3519 }
3520 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003521 case EventEntry::Type::DEVICE_RESET:
3522 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003523 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003524 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003525 break;
3526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003529 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3530 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003532
3533 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534}
3535
Svet Ganov5d3bc372020-01-26 23:11:07 -08003536void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3537 const sp<Connection>& connection) {
3538 if (connection->status == Connection::STATUS_BROKEN) {
3539 return;
3540 }
3541
3542 nsecs_t currentTime = now();
3543
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003544 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003545 connection->inputState.synthesizePointerDownEvents(currentTime);
3546
3547 if (downEvents.empty()) {
3548 return;
3549 }
3550
3551#if DEBUG_OUTBOUND_EVENT_DETAILS
3552 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3553 connection->getInputChannelName().c_str(), downEvents.size());
3554#endif
3555
3556 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003557 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003558 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3559 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003560 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003561 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003562 target.globalScaleFactor = windowInfo->globalScaleFactor;
3563 }
3564 target.inputChannel = connection->inputChannel;
3565 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003567 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003568 switch (downEventEntry->type) {
3569 case EventEntry::Type::MOTION: {
3570 logOutboundMotionDetails("down - ",
3571 static_cast<const MotionEntry&>(*downEventEntry));
3572 break;
3573 }
3574
3575 case EventEntry::Type::KEY:
3576 case EventEntry::Type::FOCUS:
3577 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003578 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003579 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003580 case EventEntry::Type::SENSOR:
3581 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003583 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003584 break;
3585 }
3586 }
3587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003588 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3589 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003590 }
3591
3592 startDispatchCycleLocked(currentTime, connection);
3593}
3594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3596 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 ALOG_ASSERT(pointerIds.value != 0);
3598
3599 uint32_t splitPointerIndexMap[MAX_POINTERS];
3600 PointerProperties splitPointerProperties[MAX_POINTERS];
3601 PointerCoords splitPointerCoords[MAX_POINTERS];
3602
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003603 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 uint32_t splitPointerCount = 0;
3605
3606 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003609 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 uint32_t pointerId = uint32_t(pointerProperties.id);
3611 if (pointerIds.hasBit(pointerId)) {
3612 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3613 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3614 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003615 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 splitPointerCount += 1;
3617 }
3618 }
3619
3620 if (splitPointerCount != pointerIds.count()) {
3621 // This is bad. We are missing some of the pointers that we expected to deliver.
3622 // Most likely this indicates that we received an ACTION_MOVE events that has
3623 // different pointer ids than we expected based on the previous ACTION_DOWN
3624 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3625 // in this way.
3626 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 "we expected there to be %d pointers. This probably means we received "
3628 "a broken sequence of pointer ids from the input device.",
3629 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003630 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 }
3632
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003633 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003635 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3636 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3638 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003639 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 uint32_t pointerId = uint32_t(pointerProperties.id);
3641 if (pointerIds.hasBit(pointerId)) {
3642 if (pointerIds.count() == 1) {
3643 // The first/last pointer went down/up.
3644 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003645 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003646 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3647 ? AMOTION_EVENT_ACTION_CANCEL
3648 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 } else {
3650 // A secondary pointer went down/up.
3651 uint32_t splitPointerIndex = 0;
3652 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3653 splitPointerIndex += 1;
3654 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003655 action = maskedAction |
3656 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658 } else {
3659 // An unrelated pointer changed.
3660 action = AMOTION_EVENT_ACTION_MOVE;
3661 }
3662 }
3663
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003664 int32_t newId = mIdGenerator.nextId();
3665 if (ATRACE_ENABLED()) {
3666 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3667 ") to MotionEvent(id=0x%" PRIx32 ").",
3668 originalMotionEntry.id, newId);
3669 ATRACE_NAME(message.c_str());
3670 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003671 std::unique_ptr<MotionEntry> splitMotionEntry =
3672 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3673 originalMotionEntry.deviceId, originalMotionEntry.source,
3674 originalMotionEntry.displayId,
3675 originalMotionEntry.policyFlags, action,
3676 originalMotionEntry.actionButton,
3677 originalMotionEntry.flags, originalMotionEntry.metaState,
3678 originalMotionEntry.buttonState,
3679 originalMotionEntry.classification,
3680 originalMotionEntry.edgeFlags,
3681 originalMotionEntry.xPrecision,
3682 originalMotionEntry.yPrecision,
3683 originalMotionEntry.xCursorPosition,
3684 originalMotionEntry.yCursorPosition,
3685 originalMotionEntry.downTime, splitPointerCount,
3686 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003688 if (originalMotionEntry.injectionState) {
3689 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 splitMotionEntry->injectionState->refCount += 1;
3691 }
3692
3693 return splitMotionEntry;
3694}
3695
3696void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3697#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003698 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699#endif
3700
3701 bool needWake;
3702 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003703 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003705 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3706 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3707 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 } // release lock
3709
3710 if (needWake) {
3711 mLooper->wake();
3712 }
3713}
3714
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003715/**
3716 * If one of the meta shortcuts is detected, process them here:
3717 * Meta + Backspace -> generate BACK
3718 * Meta + Enter -> generate HOME
3719 * This will potentially overwrite keyCode and metaState.
3720 */
3721void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003723 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3724 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3725 if (keyCode == AKEYCODE_DEL) {
3726 newKeyCode = AKEYCODE_BACK;
3727 } else if (keyCode == AKEYCODE_ENTER) {
3728 newKeyCode = AKEYCODE_HOME;
3729 }
3730 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003731 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003732 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003733 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003734 keyCode = newKeyCode;
3735 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3736 }
3737 } else if (action == AKEY_EVENT_ACTION_UP) {
3738 // In order to maintain a consistent stream of up and down events, check to see if the key
3739 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3740 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003741 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003742 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003743 auto replacementIt = mReplacedKeys.find(replacement);
3744 if (replacementIt != mReplacedKeys.end()) {
3745 keyCode = replacementIt->second;
3746 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003747 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3748 }
3749 }
3750}
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3753#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3755 "policyFlags=0x%x, action=0x%x, "
3756 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3757 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3758 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3759 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760#endif
3761 if (!validateKeyEvent(args->action)) {
3762 return;
3763 }
3764
3765 uint32_t policyFlags = args->policyFlags;
3766 int32_t flags = args->flags;
3767 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003768 // InputDispatcher tracks and generates key repeats on behalf of
3769 // whatever notifies it, so repeatCount should always be set to 0
3770 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3772 policyFlags |= POLICY_FLAG_VIRTUAL;
3773 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 if (policyFlags & POLICY_FLAG_FUNCTION) {
3776 metaState |= AMETA_FUNCTION_ON;
3777 }
3778
3779 policyFlags |= POLICY_FLAG_TRUSTED;
3780
Michael Wright78f24442014-08-06 15:55:28 -07003781 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003782 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003783
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003785 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003786 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3787 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788
Michael Wright2b3c3302018-03-02 17:19:13 +00003789 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003791 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3792 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 bool needWake;
3797 { // acquire lock
3798 mLock.lock();
3799
3800 if (shouldSendKeyToInputFilterLocked(args)) {
3801 mLock.unlock();
3802
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003803 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3805 return; // event was consumed by the filter
3806 }
3807
3808 mLock.lock();
3809 }
3810
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003811 std::unique_ptr<KeyEntry> newEntry =
3812 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3813 args->displayId, policyFlags, args->action, flags,
3814 keyCode, args->scanCode, metaState, repeatCount,
3815 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003817 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 mLock.unlock();
3819 } // release lock
3820
3821 if (needWake) {
3822 mLooper->wake();
3823 }
3824}
3825
3826bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3827 return mInputFilterEnabled;
3828}
3829
3830void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3831#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003832 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3833 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003834 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3835 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003836 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003837 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3838 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3839 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3840 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 for (uint32_t i = 0; i < args->pointerCount; i++) {
3842 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003843 "x=%f, y=%f, pressure=%f, size=%f, "
3844 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3845 "orientation=%f",
3846 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3847 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3848 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3849 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3850 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3851 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3852 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3853 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3854 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3855 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 }
3857#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003858 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3859 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 return;
3861 }
3862
3863 uint32_t policyFlags = args->policyFlags;
3864 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003865
3866 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003867 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003868 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3869 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003870 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872
3873 bool needWake;
3874 { // acquire lock
3875 mLock.lock();
3876
3877 if (shouldSendMotionToInputFilterLocked(args)) {
3878 mLock.unlock();
3879
3880 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003881 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003882 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3883 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003884 args->metaState, args->buttonState, args->classification, transform,
3885 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003886 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3887 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3888 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889
3890 policyFlags |= POLICY_FLAG_FILTERED;
3891 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3892 return; // event was consumed by the filter
3893 }
3894
3895 mLock.lock();
3896 }
3897
3898 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003899 std::unique_ptr<MotionEntry> newEntry =
3900 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3901 args->source, args->displayId, policyFlags,
3902 args->action, args->actionButton, args->flags,
3903 args->metaState, args->buttonState,
3904 args->classification, args->edgeFlags,
3905 args->xPrecision, args->yPrecision,
3906 args->xCursorPosition, args->yCursorPosition,
3907 args->downTime, args->pointerCount,
3908 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003910 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 mLock.unlock();
3912 } // release lock
3913
3914 if (needWake) {
3915 mLooper->wake();
3916 }
3917}
3918
Chris Yef59a2f42020-10-16 12:55:26 -07003919void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3920#if DEBUG_INBOUND_EVENT_DETAILS
3921 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3922 " sensorType=%s",
3923 args->id, args->eventTime, args->deviceId, args->source,
3924 NamedEnum::string(args->sensorType).c_str());
3925#endif
3926
3927 bool needWake;
3928 { // acquire lock
3929 mLock.lock();
3930
3931 // Just enqueue a new sensor event.
3932 std::unique_ptr<SensorEntry> newEntry =
3933 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3934 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3935 args->sensorType, args->accuracy,
3936 args->accuracyChanged, args->values);
3937
3938 needWake = enqueueInboundEventLocked(std::move(newEntry));
3939 mLock.unlock();
3940 } // release lock
3941
3942 if (needWake) {
3943 mLooper->wake();
3944 }
3945}
3946
Chris Yefb552902021-02-03 17:18:37 -08003947void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3948#if DEBUG_INBOUND_EVENT_DETAILS
3949 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3950 args->deviceId, args->isOn);
3951#endif
3952 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3953}
3954
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003956 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957}
3958
3959void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3960#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003961 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 "switchMask=0x%08x",
3963 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964#endif
3965
3966 uint32_t policyFlags = args->policyFlags;
3967 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003968 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969}
3970
3971void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3972#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3974 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975#endif
3976
3977 bool needWake;
3978 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003979 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003981 std::unique_ptr<DeviceResetEntry> newEntry =
3982 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3983 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 } // release lock
3985
3986 if (needWake) {
3987 mLooper->wake();
3988 }
3989}
3990
Prabir Pradhan7e186182020-11-10 13:56:45 -08003991void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3992#if DEBUG_INBOUND_EVENT_DETAILS
3993 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3994 args->enabled ? "true" : "false");
3995#endif
3996
Prabir Pradhan99987712020-11-10 18:43:05 -08003997 bool needWake;
3998 { // acquire lock
3999 std::scoped_lock _l(mLock);
4000 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
4001 args->enabled);
4002 needWake = enqueueInboundEventLocked(std::move(entry));
4003 } // release lock
4004
4005 if (needWake) {
4006 mLooper->wake();
4007 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004008}
4009
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004010InputEventInjectionResult InputDispatcher::injectInputEvent(
4011 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4012 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013#if DEBUG_INBOUND_EVENT_DETAILS
4014 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004015 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4016 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004018 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
4020 policyFlags |= POLICY_FLAG_INJECTED;
4021 if (hasInjectionPermission(injectorPid, injectorUid)) {
4022 policyFlags |= POLICY_FLAG_TRUSTED;
4023 }
4024
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004025 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004026 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4027 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4028 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4029 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4030 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004031 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004032 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004033 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004034 }
4035
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004039 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4040 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004041 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004045 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004046 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4047 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4048 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004049 int32_t keyCode = incomingKey.getKeyCode();
4050 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004051 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004053 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004054 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004055 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4056 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4057 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4060 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062
4063 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4064 android::base::Timer t;
4065 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4066 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4067 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4068 std::to_string(t.duration().count()).c_str());
4069 }
4070 }
4071
4072 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004073 std::unique_ptr<KeyEntry> injectedEntry =
4074 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004075 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004076 incomingKey.getDisplayId(), policyFlags, action,
4077 flags, keyCode, incomingKey.getScanCode(), metaState,
4078 incomingKey.getRepeatCount(),
4079 incomingKey.getDownTime());
4080 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 }
4083
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004084 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004085 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4086 int32_t action = motionEvent.getAction();
4087 size_t pointerCount = motionEvent.getPointerCount();
4088 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4089 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004090 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004091 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004093 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 }
4095
4096 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004097 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004098 android::base::Timer t;
4099 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4100 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4101 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4102 std::to_string(t.duration().count()).c_str());
4103 }
4104 }
4105
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004106 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4107 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4108 }
4109
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004111 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4112 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004113 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004114 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4115 resolvedDeviceId, motionEvent.getSource(),
4116 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004117 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004118 motionEvent.getButtonState(),
4119 motionEvent.getClassification(),
4120 motionEvent.getEdgeFlags(),
4121 motionEvent.getXPrecision(),
4122 motionEvent.getYPrecision(),
4123 motionEvent.getRawXCursorPosition(),
4124 motionEvent.getRawYCursorPosition(),
4125 motionEvent.getDownTime(), uint32_t(pointerCount),
4126 pointerProperties, samplePointerCoords,
4127 motionEvent.getXOffset(),
4128 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004129 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 sampleEventTimes += 1;
4132 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004133 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004134 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4135 resolvedDeviceId, motionEvent.getSource(),
4136 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004137 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004138 motionEvent.getMetaState(),
4139 motionEvent.getButtonState(),
4140 motionEvent.getClassification(),
4141 motionEvent.getEdgeFlags(),
4142 motionEvent.getXPrecision(),
4143 motionEvent.getYPrecision(),
4144 motionEvent.getRawXCursorPosition(),
4145 motionEvent.getRawYCursorPosition(),
4146 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004147 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004148 samplePointerCoords, motionEvent.getXOffset(),
4149 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004150 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 }
4152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004156 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004157 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159
4160 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004161 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 injectionState->injectionIsAsync = true;
4163 }
4164
4165 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004166 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
4168 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004169 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004170 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004171 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
4173
4174 mLock.unlock();
4175
4176 if (needWake) {
4177 mLooper->wake();
4178 }
4179
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004180 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004182 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004184 if (syncMode == InputEventInjectionSync::NONE) {
4185 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 } else {
4187 for (;;) {
4188 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004189 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 }
4192
4193 nsecs_t remainingTimeout = endTime - now();
4194 if (remainingTimeout <= 0) {
4195#if DEBUG_INJECTION
4196 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004199 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 break;
4201 }
4202
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004203 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 }
4205
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004206 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4207 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 while (injectionState->pendingForegroundDispatches != 0) {
4209#if DEBUG_INJECTION
4210 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212#endif
4213 nsecs_t remainingTimeout = endTime - now();
4214 if (remainingTimeout <= 0) {
4215#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4217 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 break;
4221 }
4222
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004223 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 }
4225 }
4226 }
4227
4228 injectionState->release();
4229 } // release lock
4230
4231#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004232 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234#endif
4235
4236 return injectionResult;
4237}
4238
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004239std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004240 std::array<uint8_t, 32> calculatedHmac;
4241 std::unique_ptr<VerifiedInputEvent> result;
4242 switch (event.getType()) {
4243 case AINPUT_EVENT_TYPE_KEY: {
4244 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4245 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4246 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004247 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004248 break;
4249 }
4250 case AINPUT_EVENT_TYPE_MOTION: {
4251 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4252 VerifiedMotionEvent verifiedMotionEvent =
4253 verifiedMotionEventFromMotionEvent(motionEvent);
4254 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004255 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004256 break;
4257 }
4258 default: {
4259 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4260 return nullptr;
4261 }
4262 }
4263 if (calculatedHmac == INVALID_HMAC) {
4264 return nullptr;
4265 }
4266 if (calculatedHmac != event.getHmac()) {
4267 return nullptr;
4268 }
4269 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004270}
4271
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 return injectorUid == 0 ||
4274 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275}
4276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004277void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004278 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 if (injectionState) {
4281#if DEBUG_INJECTION
4282 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 "injectorPid=%d, injectorUid=%d",
4284 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285#endif
4286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 // Log the outcome since the injector did not wait for the injection result.
4289 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004290 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 ALOGV("Asynchronous input event injection succeeded.");
4292 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004293 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 ALOGW("Asynchronous input event injection failed.");
4295 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004296 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 ALOGW("Asynchronous input event injection permission denied.");
4298 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004299 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 ALOGW("Asynchronous input event injection timed out.");
4301 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004302 case InputEventInjectionResult::PENDING:
4303 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306 }
4307
4308 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004309 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311}
4312
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4314 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 if (injectionState) {
4316 injectionState->pendingForegroundDispatches += 1;
4317 }
4318}
4319
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004320void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4321 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 if (injectionState) {
4323 injectionState->pendingForegroundDispatches -= 1;
4324
4325 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004326 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328 }
4329}
4330
chaviw3277faf2021-05-19 16:45:23 -05004331const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004332 int32_t displayId) const {
chaviw3277faf2021-05-19 16:45:23 -05004333 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004334 auto it = mWindowHandlesByDisplay.find(displayId);
4335 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004336}
4337
chaviw3277faf2021-05-19 16:45:23 -05004338sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004339 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004340 if (windowHandleToken == nullptr) {
4341 return nullptr;
4342 }
4343
Arthur Hungb92218b2018-08-14 12:00:21 +08004344 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004345 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4346 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004347 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004348 return windowHandle;
4349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
4351 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004352 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353}
4354
chaviw3277faf2021-05-19 16:45:23 -05004355sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4356 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004357 if (windowHandleToken == nullptr) {
4358 return nullptr;
4359 }
4360
chaviw3277faf2021-05-19 16:45:23 -05004361 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004362 if (windowHandle->getToken() == windowHandleToken) {
4363 return windowHandle;
4364 }
4365 }
4366 return nullptr;
4367}
4368
chaviw3277faf2021-05-19 16:45:23 -05004369sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4370 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004371 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004372 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4373 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004374 if (handle->getId() == windowHandle->getId() &&
4375 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004376 if (windowHandle->getInfo()->displayId != it.first) {
4377 ALOGE("Found window %s in display %" PRId32
4378 ", but it should belong to display %" PRId32,
4379 windowHandle->getName().c_str(), it.first,
4380 windowHandle->getInfo()->displayId);
4381 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004382 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004386 return nullptr;
4387}
4388
chaviw3277faf2021-05-19 16:45:23 -05004389sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004390 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4391 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392}
4393
chaviw3277faf2021-05-19 16:45:23 -05004394bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004395 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4396 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004397 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004398 if (connection != nullptr && noInputChannel) {
4399 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4400 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4401 return false;
4402 }
4403
4404 if (connection == nullptr) {
4405 if (!noInputChannel) {
4406 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4407 }
4408 return false;
4409 }
4410 if (!connection->responsive) {
4411 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4412 return false;
4413 }
4414 return true;
4415}
4416
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004417std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4418 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004419 auto connectionIt = mConnectionsByToken.find(token);
4420 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004421 return nullptr;
4422 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004423 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004424}
4425
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004426void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw3277faf2021-05-19 16:45:23 -05004427 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4428 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004429 // Remove all handles on a display if there are no windows left.
4430 mWindowHandlesByDisplay.erase(displayId);
4431 return;
4432 }
4433
4434 // Since we compare the pointer of input window handles across window updates, we need
4435 // to make sure the handle object for the same window stays unchanged across updates.
chaviw3277faf2021-05-19 16:45:23 -05004436 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4437 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4438 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004439 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004440 }
4441
chaviw3277faf2021-05-19 16:45:23 -05004442 std::vector<sp<WindowInfoHandle>> newHandles;
4443 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw3277faf2021-05-19 16:45:23 -05004444 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004445 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4446 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4447 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004448 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4449 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4450 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004451 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004452 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004453 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004454 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004455 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004456 }
4457
4458 if (info->displayId != displayId) {
4459 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4460 handle->getName().c_str(), displayId, info->displayId);
4461 continue;
4462 }
4463
Robert Carredd13602020-04-13 17:24:34 -07004464 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4465 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw3277faf2021-05-19 16:45:23 -05004466 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004467 oldHandle->updateFrom(handle);
4468 newHandles.push_back(oldHandle);
4469 } else {
4470 newHandles.push_back(handle);
4471 }
4472 }
4473
4474 // Insert or replace
4475 mWindowHandlesByDisplay[displayId] = newHandles;
4476}
4477
Arthur Hung72d8dc32020-03-28 00:48:39 +00004478void InputDispatcher::setInputWindows(
chaviw3277faf2021-05-19 16:45:23 -05004479 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004480 { // acquire lock
4481 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004482 for (const auto& [displayId, handles] : handlesPerDisplay) {
4483 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004484 }
4485 }
4486 // Wake up poll loop since it may need to make new input dispatching choices.
4487 mLooper->wake();
4488}
4489
Arthur Hungb92218b2018-08-14 12:00:21 +08004490/**
4491 * Called from InputManagerService, update window handle list by displayId that can receive input.
4492 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4493 * If set an empty list, remove all handles from the specific display.
4494 * For focused handle, check if need to change and send a cancel event to previous one.
4495 * For removed handle, check if need to send a cancel event if already in touch.
4496 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004497void InputDispatcher::setInputWindowsLocked(
chaviw3277faf2021-05-19 16:45:23 -05004498 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004499 if (DEBUG_FOCUS) {
4500 std::string windowList;
chaviw3277faf2021-05-19 16:45:23 -05004501 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004502 windowList += iwh->getName() + " ";
4503 }
4504 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004507 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw3277faf2021-05-19 16:45:23 -05004508 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004509 const bool noInputWindow =
chaviw3277faf2021-05-19 16:45:23 -05004510 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004511 if (noInputWindow && window->getToken() != nullptr) {
4512 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4513 window->getName().c_str());
4514 window->releaseChannel();
4515 }
4516 }
4517
Arthur Hung72d8dc32020-03-28 00:48:39 +00004518 // Copy old handles for release if they are no longer present.
chaviw3277faf2021-05-19 16:45:23 -05004519 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004521 // Save the old windows' orientation by ID before it gets updated.
4522 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw3277faf2021-05-19 16:45:23 -05004523 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004524 oldWindowOrientations.emplace(handle->getId(),
4525 handle->getInfo()->transform.getOrientation());
4526 }
4527
chaviw3277faf2021-05-19 16:45:23 -05004528 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004529
chaviw3277faf2021-05-19 16:45:23 -05004530 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004531 if (mLastHoverWindowHandle &&
4532 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4533 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004534 mLastHoverWindowHandle = nullptr;
4535 }
4536
Vishnu Nairc519ff72021-01-21 08:23:08 -08004537 std::optional<FocusResolver::FocusChanges> changes =
4538 mFocusResolver.setInputWindows(displayId, windowHandles);
4539 if (changes) {
4540 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004543 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4544 mTouchStatesByDisplay.find(displayId);
4545 if (stateIt != mTouchStatesByDisplay.end()) {
4546 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004547 for (size_t i = 0; i < state.windows.size();) {
4548 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004549 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004550 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004551 ALOGD("Touched window was removed: %s in display %" PRId32,
4552 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004553 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004554 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004555 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4556 if (touchedInputChannel != nullptr) {
4557 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4558 "touched window was removed");
4559 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004561 state.windows.erase(state.windows.begin() + i);
4562 } else {
4563 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 }
4565 }
arthurhungb89ccb02020-12-30 16:19:01 +08004566
arthurhung6d4bed92021-03-17 11:59:33 +08004567 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004568 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004569 if (mDragState &&
4570 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004571 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004572 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004573 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004574 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004575
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004576 if (isPerWindowInputRotationEnabled()) {
4577 // Determine if the orientation of any of the input windows have changed, and cancel all
4578 // pointer events if necessary.
chaviw3277faf2021-05-19 16:45:23 -05004579 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4580 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004581 if (newWindowHandle != nullptr &&
4582 newWindowHandle->getInfo()->transform.getOrientation() !=
4583 oldWindowOrientations[oldWindowHandle->getId()]) {
4584 std::shared_ptr<InputChannel> inputChannel =
4585 getInputChannelLocked(newWindowHandle->getToken());
4586 if (inputChannel != nullptr) {
4587 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4588 "touched window's orientation changed");
4589 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4590 }
4591 }
4592 }
4593 }
4594
Arthur Hung72d8dc32020-03-28 00:48:39 +00004595 // Release information for windows that are no longer present.
4596 // This ensures that unused input channels are released promptly.
4597 // Otherwise, they might stick around until the window handle is destroyed
4598 // which might not happen until the next GC.
chaviw3277faf2021-05-19 16:45:23 -05004599 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004600 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004601 if (DEBUG_FOCUS) {
4602 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004603 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004604 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004605 // To avoid making too many calls into the compat framework, only
4606 // check for window flags when windows are going away.
4607 // TODO(b/157929241) : delete this. This is only needed temporarily
4608 // in order to gather some data about the flag usage
chaviw3277faf2021-05-19 16:45:23 -05004609 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004610 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4611 oldWindowHandle->getName().c_str());
4612 if (mCompatService != nullptr) {
4613 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4614 oldWindowHandle->getInfo()->ownerUid);
4615 }
4616 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004617 }
chaviw291d88a2019-02-14 10:33:58 -08004618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619}
4620
4621void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004622 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004623 if (DEBUG_FOCUS) {
4624 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4625 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4626 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004627 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004628 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004629 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 } // release lock
4631
4632 // Wake up poll loop since it may need to make new input dispatching choices.
4633 mLooper->wake();
4634}
4635
Vishnu Nair599f1412021-06-21 10:39:58 -07004636void InputDispatcher::setFocusedApplicationLocked(
4637 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4638 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4639 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4640
4641 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4642 return; // This application is already focused. No need to wake up or change anything.
4643 }
4644
4645 // Set the new application handle.
4646 if (inputApplicationHandle != nullptr) {
4647 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4648 } else {
4649 mFocusedApplicationHandlesByDisplay.erase(displayId);
4650 }
4651
4652 // No matter what the old focused application was, stop waiting on it because it is
4653 // no longer focused.
4654 resetNoFocusedWindowTimeoutLocked();
4655}
4656
Tiger Huang721e26f2018-07-24 22:26:19 +08004657/**
4658 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4659 * the display not specified.
4660 *
4661 * We track any unreleased events for each window. If a window loses the ability to receive the
4662 * released event, we will send a cancel event to it. So when the focused display is changed, we
4663 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4664 * display. The display-specified events won't be affected.
4665 */
4666void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004667 if (DEBUG_FOCUS) {
4668 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4669 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004670 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004671 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004672
4673 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004674 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004675 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004676 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004677 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004678 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004679 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680 CancelationOptions
4681 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4682 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004683 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004684 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4685 }
4686 }
4687 mFocusedDisplayId = displayId;
4688
Chris Ye3c2d6f52020-08-09 10:39:48 -07004689 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004690 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004691 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004692
Vishnu Nairad321cd2020-08-20 16:40:21 -07004693 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004694 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004695 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004696 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004697 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004698 }
4699 }
4700 }
4701
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004702 if (DEBUG_FOCUS) {
4703 logDispatchStateLocked();
4704 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004705 } // release lock
4706
4707 // Wake up poll loop since it may need to make new input dispatching choices.
4708 mLooper->wake();
4709}
4710
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004712 if (DEBUG_FOCUS) {
4713 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715
4716 bool changed;
4717 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004718 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719
4720 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4721 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004722 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 }
4724
4725 if (mDispatchEnabled && !enabled) {
4726 resetAndDropEverythingLocked("dispatcher is being disabled");
4727 }
4728
4729 mDispatchEnabled = enabled;
4730 mDispatchFrozen = frozen;
4731 changed = true;
4732 } else {
4733 changed = false;
4734 }
4735
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004736 if (DEBUG_FOCUS) {
4737 logDispatchStateLocked();
4738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 } // release lock
4740
4741 if (changed) {
4742 // Wake up poll loop since it may need to make new input dispatching choices.
4743 mLooper->wake();
4744 }
4745}
4746
4747void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004748 if (DEBUG_FOCUS) {
4749 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751
4752 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004753 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754
4755 if (mInputFilterEnabled == enabled) {
4756 return;
4757 }
4758
4759 mInputFilterEnabled = enabled;
4760 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4761 } // release lock
4762
4763 // Wake up poll loop since there might be work to do to drop everything.
4764 mLooper->wake();
4765}
4766
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004767void InputDispatcher::setInTouchMode(bool inTouchMode) {
4768 std::scoped_lock lock(mLock);
4769 mInTouchMode = inTouchMode;
4770}
4771
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004772void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4773 if (opacity < 0 || opacity > 1) {
4774 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4775 return;
4776 }
4777
4778 std::scoped_lock lock(mLock);
4779 mMaximumObscuringOpacityForTouch = opacity;
4780}
4781
4782void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4783 std::scoped_lock lock(mLock);
4784 mBlockUntrustedTouchesMode = mode;
4785}
4786
arthurhungb89ccb02020-12-30 16:19:01 +08004787bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4788 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004789 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004790 if (DEBUG_FOCUS) {
4791 ALOGD("Trivial transfer to same window.");
4792 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004793 return true;
4794 }
4795
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004797 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798
chaviw3277faf2021-05-19 16:45:23 -05004799 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4800 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004801 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004802 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 return false;
4804 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004805 if (DEBUG_FOCUS) {
4806 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4807 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004810 if (DEBUG_FOCUS) {
4811 ALOGD("Cannot transfer focus because windows are on different displays.");
4812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 return false;
4814 }
4815
4816 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004817 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4818 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004819 for (size_t i = 0; i < state.windows.size(); i++) {
4820 const TouchedWindow& touchedWindow = state.windows[i];
4821 if (touchedWindow.windowHandle == fromWindowHandle) {
4822 int32_t oldTargetFlags = touchedWindow.targetFlags;
4823 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004825 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 int32_t newTargetFlags = oldTargetFlags &
4828 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4829 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004830 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831
arthurhungb89ccb02020-12-30 16:19:01 +08004832 // Store the dragging window.
4833 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004834 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004835 }
4836
Jeff Brownf086ddb2014-02-11 14:28:48 -08004837 found = true;
4838 goto Found;
4839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 }
4841 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004845 if (DEBUG_FOCUS) {
4846 ALOGD("Focus transfer failed because from window did not have focus.");
4847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 return false;
4849 }
4850
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004851 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4852 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004853 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004854 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004855 CancelationOptions
4856 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4857 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004859 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 }
4861
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004862 if (DEBUG_FOCUS) {
4863 logDispatchStateLocked();
4864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 } // release lock
4866
4867 // Wake up poll loop since it may need to make new input dispatching choices.
4868 mLooper->wake();
4869 return true;
4870}
4871
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004872// Binder call
4873bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4874 sp<IBinder> fromToken;
4875 { // acquire lock
4876 std::scoped_lock _l(mLock);
4877
chaviw3277faf2021-05-19 16:45:23 -05004878 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004879 if (toWindowHandle == nullptr) {
4880 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4881 return false;
4882 }
4883
4884 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4885
4886 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4887 if (touchStateIt == mTouchStatesByDisplay.end()) {
4888 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4889 displayId);
4890 return false;
4891 }
4892
4893 TouchState& state = touchStateIt->second;
4894 if (state.windows.size() != 1) {
4895 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4896 state.windows.size());
4897 return false;
4898 }
4899 const TouchedWindow& touchedWindow = state.windows[0];
4900 fromToken = touchedWindow.windowHandle->getToken();
4901 } // release lock
4902
4903 return transferTouchFocus(fromToken, destChannelToken);
4904}
4905
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004907 if (DEBUG_FOCUS) {
4908 ALOGD("Resetting and dropping all events (%s).", reason);
4909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
4911 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4912 synthesizeCancelationEventsForAllConnectionsLocked(options);
4913
4914 resetKeyRepeatLocked();
4915 releasePendingEventLocked();
4916 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004917 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004920 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004922 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923}
4924
4925void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004926 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 dumpDispatchStateLocked(dump);
4928
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004929 std::istringstream stream(dump);
4930 std::string line;
4931
4932 while (std::getline(stream, line, '\n')) {
4933 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 }
4935}
4936
Prabir Pradhan99987712020-11-10 18:43:05 -08004937std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4938 std::string dump;
4939
4940 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4941 toString(mFocusedWindowRequestedPointerCapture));
4942
4943 std::string windowName = "None";
4944 if (mWindowTokenWithPointerCapture) {
chaviw3277faf2021-05-19 16:45:23 -05004945 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004946 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4947 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4948 : "token has capture without window";
4949 }
4950 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4951
4952 return dump;
4953}
4954
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004955void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004956 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4957 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4958 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004959 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960
Tiger Huang721e26f2018-07-24 22:26:19 +08004961 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4962 dump += StringPrintf(INDENT "FocusedApplications:\n");
4963 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4964 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004965 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004966 const std::chrono::duration timeout =
4967 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004968 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004969 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004970 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004973 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004975
Vishnu Nairc519ff72021-01-21 08:23:08 -08004976 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004977 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004979 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004980 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004981 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4982 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004983 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 state.displayId, toString(state.down), toString(state.split),
4985 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004986 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004987 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004988 for (size_t i = 0; i < state.windows.size(); i++) {
4989 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004990 dump += StringPrintf(INDENT4
4991 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4992 i, touchedWindow.windowHandle->getName().c_str(),
4993 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004994 }
4995 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004996 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004997 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004998 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004999 dump += INDENT3 "Portal windows:\n";
5000 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005001 const sp<WindowInfoHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005002 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5003 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005004 }
5005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 }
5007 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005008 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 }
5010
arthurhung6d4bed92021-03-17 11:59:33 +08005011 if (mDragState) {
5012 dump += StringPrintf(INDENT "DragState:\n");
5013 mDragState->dump(dump, INDENT2);
5014 }
5015
Arthur Hungb92218b2018-08-14 12:00:21 +08005016 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005017 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05005018 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005019 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005020 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005021 dump += INDENT2 "Windows:\n";
5022 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005023 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5024 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005026 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005027 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005028 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005029 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005030 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005031 "applicationInfo.name=%s, "
5032 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005033 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005034 i, windowInfo->name.c_str(), windowInfo->id,
5035 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005037 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005038 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005039 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005040 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005041 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005042 windowInfo->frameLeft, windowInfo->frameTop,
5043 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005044 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005045 windowInfo->applicationInfo.name.c_str(),
5046 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005047 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005048 dump += StringPrintf(", inputFeatures=%s",
5049 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005050 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005051 "ms, trustedOverlay=%s, hasToken=%s, "
5052 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005053 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005054 millis(windowInfo->dispatchingTimeout),
5055 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005056 toString(windowInfo->token != nullptr),
5057 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005058 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005059 }
5060 } else {
5061 dump += INDENT2 "Windows: <none>\n";
5062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 }
5064 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005065 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 }
5067
Michael Wright3dd60e22019-03-27 22:06:44 +00005068 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005069 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005070 const std::vector<Monitor>& monitors = it.second;
5071 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5072 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005073 }
5074 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 const std::vector<Monitor>& monitors = it.second;
5076 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5077 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005080 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 }
5082
5083 nsecs_t currentTime = now();
5084
5085 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005086 if (!mRecentQueue.empty()) {
5087 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005088 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005089 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005090 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005091 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 }
5093 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005094 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 }
5096
5097 // Dump event currently being dispatched.
5098 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += INDENT "PendingEvent:\n";
5100 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005101 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005102 dump += StringPrintf(", age=%" PRId64 "ms\n",
5103 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005105 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 }
5107
5108 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005109 if (!mInboundQueue.empty()) {
5110 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005111 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005112 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005113 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005114 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 }
5116 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005117 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 }
5119
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005120 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005121 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005122 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5123 const KeyReplacement& replacement = pair.first;
5124 int32_t newKeyCode = pair.second;
5125 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005126 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005127 }
5128 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005129 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005130 }
5131
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005132 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005133 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005134 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005135 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005136 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005137 connection->inputChannel->getFd().get(),
5138 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005139 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005140 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005142 if (!connection->outboundQueue.empty()) {
5143 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5144 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005145 dump += dumpQueue(connection->outboundQueue, currentTime);
5146
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005148 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 }
5150
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005151 if (!connection->waitQueue.empty()) {
5152 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5153 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005154 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005156 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 }
5158 }
5159 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005160 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 }
5162
5163 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005164 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5165 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005167 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 }
5169
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005170 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005171 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5172 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5173 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005174 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005175 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176}
5177
Michael Wright3dd60e22019-03-27 22:06:44 +00005178void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5179 const size_t numMonitors = monitors.size();
5180 for (size_t i = 0; i < numMonitors; i++) {
5181 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005182 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005183 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5184 dump += "\n";
5185 }
5186}
5187
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005188class LooperEventCallback : public LooperCallback {
5189public:
5190 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5191 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5192
5193private:
5194 std::function<int(int events)> mCallback;
5195};
5196
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005197Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005198#if DEBUG_CHANNEL_CREATION
5199 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200#endif
5201
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005202 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005203 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005204 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005205
5206 if (result) {
5207 return base::Error(result) << "Failed to open input channel pair with name " << name;
5208 }
5209
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005211 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005212 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005213 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005214 sp<Connection> connection =
5215 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005217 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5218 ALOGE("Created a new connection, but the token %p is already known", token.get());
5219 }
5220 mConnectionsByToken.emplace(token, connection);
5221
5222 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5223 this, std::placeholders::_1, token);
5224
5225 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226 } // release lock
5227
5228 // Wake the looper because some connections have changed.
5229 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005230 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231}
5232
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005233Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5234 bool isGestureMonitor,
5235 const std::string& name,
5236 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005237 std::shared_ptr<InputChannel> serverChannel;
5238 std::unique_ptr<InputChannel> clientChannel;
5239 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5240 if (result) {
5241 return base::Error(result) << "Failed to open input channel pair with name " << name;
5242 }
5243
Michael Wright3dd60e22019-03-27 22:06:44 +00005244 { // acquire lock
5245 std::scoped_lock _l(mLock);
5246
5247 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005248 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5249 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005250 }
5251
Garfield Tan15601662020-09-22 15:32:38 -07005252 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005253 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005254 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005255
5256 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5257 ALOGE("Created a new connection, but the token %p is already known", token.get());
5258 }
5259 mConnectionsByToken.emplace(token, connection);
5260 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5261 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005263 auto& monitorsByDisplay =
5264 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005265 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005266
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005267 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005268 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5269 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005270 }
Garfield Tan15601662020-09-22 15:32:38 -07005271
Michael Wright3dd60e22019-03-27 22:06:44 +00005272 // Wake the looper because some connections have changed.
5273 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005274 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005275}
5276
Garfield Tan15601662020-09-22 15:32:38 -07005277status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005279 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280
Garfield Tan15601662020-09-22 15:32:38 -07005281 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 if (status) {
5283 return status;
5284 }
5285 } // release lock
5286
5287 // Wake the poll loop because removing the connection may have changed the current
5288 // synchronization state.
5289 mLooper->wake();
5290 return OK;
5291}
5292
Garfield Tan15601662020-09-22 15:32:38 -07005293status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5294 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005295 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005296 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005297 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 return BAD_VALUE;
5299 }
5300
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005301 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005302
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005304 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 }
5306
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005307 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308
5309 nsecs_t currentTime = now();
5310 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5311
5312 connection->status = Connection::STATUS_ZOMBIE;
5313 return OK;
5314}
5315
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005316void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5317 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5318 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005319}
5320
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005321void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005322 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005323 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005324 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005325 std::vector<Monitor>& monitors = it->second;
5326 const size_t numMonitors = monitors.size();
5327 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005328 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005329 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5330 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005331 monitors.erase(monitors.begin() + i);
5332 break;
5333 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005334 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005335 if (monitors.empty()) {
5336 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005337 } else {
5338 ++it;
5339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 }
5341}
5342
Michael Wright3dd60e22019-03-27 22:06:44 +00005343status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5344 { // acquire lock
5345 std::scoped_lock _l(mLock);
5346 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5347
5348 if (!foundDisplayId) {
5349 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5350 return BAD_VALUE;
5351 }
5352 int32_t displayId = foundDisplayId.value();
5353
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005354 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5355 mTouchStatesByDisplay.find(displayId);
5356 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005357 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5358 return BAD_VALUE;
5359 }
5360
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005361 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005362 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005363 std::optional<int32_t> foundDeviceId;
5364 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005365 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005366 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005367 foundDeviceId = state.deviceId;
5368 }
5369 }
5370 if (!foundDeviceId || !state.down) {
5371 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005372 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005373 return BAD_VALUE;
5374 }
5375 int32_t deviceId = foundDeviceId.value();
5376
5377 // Send cancel events to all the input channels we're stealing from.
5378 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005379 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005380 options.deviceId = deviceId;
5381 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005382 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005383 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005384 std::shared_ptr<InputChannel> channel =
5385 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005386 if (channel != nullptr) {
5387 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005388 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005389 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005390 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005391 canceledWindows += "]";
5392 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5393 canceledWindows.c_str());
5394
Michael Wright3dd60e22019-03-27 22:06:44 +00005395 // Then clear the current touch state so we stop dispatching to them as well.
5396 state.filterNonMonitors();
5397 }
5398 return OK;
5399}
5400
Prabir Pradhan99987712020-11-10 18:43:05 -08005401void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5402 { // acquire lock
5403 std::scoped_lock _l(mLock);
5404 if (DEBUG_FOCUS) {
chaviw3277faf2021-05-19 16:45:23 -05005405 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005406 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5407 windowHandle != nullptr ? windowHandle->getName().c_str()
5408 : "token without window");
5409 }
5410
Vishnu Nairc519ff72021-01-21 08:23:08 -08005411 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005412 if (focusedToken != windowToken) {
5413 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5414 enabled ? "enable" : "disable");
5415 return;
5416 }
5417
5418 if (enabled == mFocusedWindowRequestedPointerCapture) {
5419 ALOGW("Ignoring request to %s Pointer Capture: "
5420 "window has %s requested pointer capture.",
5421 enabled ? "enable" : "disable", enabled ? "already" : "not");
5422 return;
5423 }
5424
5425 mFocusedWindowRequestedPointerCapture = enabled;
5426 setPointerCaptureLocked(enabled);
5427 } // release lock
5428
5429 // Wake the thread to process command entries.
5430 mLooper->wake();
5431}
5432
Michael Wright3dd60e22019-03-27 22:06:44 +00005433std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5434 const sp<IBinder>& token) {
5435 for (const auto& it : mGestureMonitorsByDisplay) {
5436 const std::vector<Monitor>& monitors = it.second;
5437 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005438 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005439 return it.first;
5440 }
5441 }
5442 }
5443 return std::nullopt;
5444}
5445
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005446std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5447 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5448 if (gesturePid.has_value()) {
5449 return gesturePid;
5450 }
5451 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5452}
5453
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005454sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005455 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005456 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005457 }
5458
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005459 for (const auto& [token, connection] : mConnectionsByToken) {
5460 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005461 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 }
5463 }
Robert Carr4e670e52018-08-15 13:26:12 -07005464
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005465 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466}
5467
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005468std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5469 sp<Connection> connection = getConnectionLocked(connectionToken);
5470 if (connection == nullptr) {
5471 return "<nullptr>";
5472 }
5473 return connection->getInputChannelName();
5474}
5475
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005476void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005477 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005478 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005479}
5480
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005481void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5482 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005483 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005484 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5485 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 commandEntry->connection = connection;
5487 commandEntry->eventTime = currentTime;
5488 commandEntry->seq = seq;
5489 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005490 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005491 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492}
5493
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005494void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5495 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005497 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005499 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5500 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005502 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503}
5504
Vishnu Nairad321cd2020-08-20 16:40:21 -07005505void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5506 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005507 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5508 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005509 commandEntry->oldToken = oldToken;
5510 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005511 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005512}
5513
arthurhungf452d0b2021-01-06 00:19:52 +08005514void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5515 std::unique_ptr<CommandEntry> commandEntry =
5516 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5517 commandEntry->newToken = token;
5518 commandEntry->x = x;
5519 commandEntry->y = y;
5520 postCommandLocked(std::move(commandEntry));
5521}
5522
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005523void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5524 if (connection == nullptr) {
5525 LOG_ALWAYS_FATAL("Caller must check for nullness");
5526 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005527 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5528 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005529 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005530 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005531 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005532 return;
5533 }
5534 /**
5535 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5536 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5537 * has changed. This could cause newer entries to time out before the already dispatched
5538 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5539 * processes the events linearly. So providing information about the oldest entry seems to be
5540 * most useful.
5541 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005542 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005543 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5544 std::string reason =
5545 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005546 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005547 ns2ms(currentWait),
5548 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005549 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005550 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005551
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005552 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5553
5554 // Stop waking up for events on this connection, it is already unresponsive
5555 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005556}
5557
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005558void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5559 std::string reason =
5560 StringPrintf("%s does not have a focused window", application->getName().c_str());
5561 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005563 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5564 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5565 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005566 postCommandLocked(std::move(commandEntry));
5567}
5568
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005569void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5570 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5571 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5572 commandEntry->obscuringPackage = obscuringPackage;
5573 postCommandLocked(std::move(commandEntry));
5574}
5575
chaviw3277faf2021-05-19 16:45:23 -05005576void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005577 const std::string& reason) {
5578 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5579 updateLastAnrStateLocked(windowLabel, reason);
5580}
5581
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005582void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5583 const std::string& reason) {
5584 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005585 updateLastAnrStateLocked(windowLabel, reason);
5586}
5587
5588void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5589 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005591 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592 struct tm tm;
5593 localtime_r(&t, &tm);
5594 char timestr[64];
5595 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005596 mLastAnrState.clear();
5597 mLastAnrState += INDENT "ANR:\n";
5598 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005599 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5600 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005601 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602}
5603
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005604void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 mLock.unlock();
5606
5607 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5608
5609 mLock.lock();
5610}
5611
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005612void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 sp<Connection> connection = commandEntry->connection;
5614
5615 if (connection->status != Connection::STATUS_ZOMBIE) {
5616 mLock.unlock();
5617
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005618 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619
5620 mLock.lock();
5621 }
5622}
5623
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005624void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005625 sp<IBinder> oldToken = commandEntry->oldToken;
5626 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005627 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005628 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005629 mLock.lock();
5630}
5631
arthurhungf452d0b2021-01-06 00:19:52 +08005632void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5633 sp<IBinder> newToken = commandEntry->newToken;
5634 mLock.unlock();
5635 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5636 mLock.lock();
5637}
5638
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005639void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005641
5642 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5643
5644 mLock.lock();
5645}
5646
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005647void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005648 mLock.unlock();
5649
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005650 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651
5652 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005653}
5654
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005655void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005656 mLock.unlock();
5657
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005658 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5659
5660 mLock.lock();
5661}
5662
5663void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5664 mLock.unlock();
5665
5666 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5667
5668 mLock.lock();
5669}
5670
5671void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5672 mLock.unlock();
5673
5674 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005675
5676 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005677}
5678
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005679void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5680 mLock.unlock();
5681
5682 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5683
5684 mLock.lock();
5685}
5686
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5688 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005689 KeyEntry& entry = *(commandEntry->keyEntry);
5690 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691
5692 mLock.unlock();
5693
Michael Wright2b3c3302018-03-02 17:19:13 +00005694 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005695 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005696 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005697 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5698 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005699 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701
5702 mLock.lock();
5703
5704 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005705 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005707 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005709 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5710 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712}
5713
chaviwfd6d3512019-03-25 13:23:49 -07005714void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5715 mLock.unlock();
5716 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5717 mLock.lock();
5718}
5719
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005720/**
5721 * Connection is responsive if it has no events in the waitQueue that are older than the
5722 * current time.
5723 */
5724static bool isConnectionResponsive(const Connection& connection) {
5725 const nsecs_t currentTime = now();
5726 for (const DispatchEntry* entry : connection.waitQueue) {
5727 if (entry->timeoutTime < currentTime) {
5728 return false;
5729 }
5730 }
5731 return true;
5732}
5733
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005734void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005736 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005738 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739
5740 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005741 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005742 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005743 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005745 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005746 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005747 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005748 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5749 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005750 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005751 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5752 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5753 connection->inputChannel->getConnectionToken(),
5754 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5755 finishTime);
5756 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005757
5758 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005759 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005760 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005761 restartEvent =
5762 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005763 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005764 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005765 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5766 handled);
5767 } else {
5768 restartEvent = false;
5769 }
5770
5771 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005772 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005773 // contents of the wait queue to have been drained, so we need to double-check
5774 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005775 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5776 if (dispatchEntryIt != connection->waitQueue.end()) {
5777 dispatchEntry = *dispatchEntryIt;
5778 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005779 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5780 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005781 if (!connection->responsive) {
5782 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005783 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005784 // The connection was unresponsive, and now it's responsive.
5785 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005786 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005787 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005788 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005789 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005790 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005791 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005792 } else {
5793 releaseDispatchEntry(dispatchEntry);
5794 }
5795 }
5796
5797 // Start the next dispatch cycle for this connection.
5798 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799}
5800
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005801void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5802 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5803 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5804 monitorUnresponsiveCommand->pid = pid;
5805 monitorUnresponsiveCommand->reason = std::move(reason);
5806 postCommandLocked(std::move(monitorUnresponsiveCommand));
5807}
5808
5809void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5810 std::string reason) {
5811 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5812 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5813 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5814 windowUnresponsiveCommand->reason = std::move(reason);
5815 postCommandLocked(std::move(windowUnresponsiveCommand));
5816}
5817
5818void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5819 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5820 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5821 monitorResponsiveCommand->pid = pid;
5822 postCommandLocked(std::move(monitorResponsiveCommand));
5823}
5824
5825void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5826 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5827 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5828 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5829 postCommandLocked(std::move(windowResponsiveCommand));
5830}
5831
5832/**
5833 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5834 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5835 * command entry to the command queue.
5836 */
5837void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5838 std::string reason) {
5839 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5840 if (connection.monitor) {
5841 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5842 reason.c_str());
5843 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5844 if (!pid.has_value()) {
5845 ALOGE("Could not find unresponsive monitor for connection %s",
5846 connection.inputChannel->getName().c_str());
5847 return;
5848 }
5849 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5850 return;
5851 }
5852 // If not a monitor, must be a window
5853 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5854 reason.c_str());
5855 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5856}
5857
5858/**
5859 * Tell the policy that a connection has become responsive so that it can stop ANR.
5860 */
5861void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5862 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5863 if (connection.monitor) {
5864 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5865 if (!pid.has_value()) {
5866 ALOGE("Could not find responsive monitor for connection %s",
5867 connection.inputChannel->getName().c_str());
5868 return;
5869 }
5870 sendMonitorResponsiveCommandLocked(pid.value());
5871 return;
5872 }
5873 // If not a monitor, must be a window
5874 sendWindowResponsiveCommandLocked(connectionToken);
5875}
5876
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005878 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005879 KeyEntry& keyEntry, bool handled) {
5880 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005881 if (!handled) {
5882 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005883 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005884 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005885 return false;
5886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005888 // Get the fallback key state.
5889 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005890 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005891 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005892 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005893 connection->inputState.removeFallbackKey(originalKeyCode);
5894 }
5895
5896 if (handled || !dispatchEntry->hasForegroundTarget()) {
5897 // If the application handles the original key for which we previously
5898 // generated a fallback or if the window is not a foreground window,
5899 // then cancel the associated fallback key, if any.
5900 if (fallbackKeyCode != -1) {
5901 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005903 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005904 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005905 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005907 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005908 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909
5910 mLock.unlock();
5911
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005912 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005913 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914
5915 mLock.lock();
5916
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005917 // Cancel the fallback key.
5918 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005920 "application handled the original non-fallback key "
5921 "or is no longer a foreground target, "
5922 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 options.keyCode = fallbackKeyCode;
5924 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005926 connection->inputState.removeFallbackKey(originalKeyCode);
5927 }
5928 } else {
5929 // If the application did not handle a non-fallback key, first check
5930 // that we are in a good state to perform unhandled key event processing
5931 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005933 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005935 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005936 "since this is not an initial down. "
5937 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005938 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 return false;
5941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005943 // Dispatch the unhandled key to the policy.
5944#if DEBUG_OUTBOUND_EVENT_DETAILS
5945 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005946 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005947 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005949 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005950
5951 mLock.unlock();
5952
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005953 bool fallback =
5954 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005955 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956
5957 mLock.lock();
5958
5959 if (connection->status != Connection::STATUS_NORMAL) {
5960 connection->inputState.removeFallbackKey(originalKeyCode);
5961 return false;
5962 }
5963
5964 // Latch the fallback keycode for this key on an initial down.
5965 // The fallback keycode cannot change at any other point in the lifecycle.
5966 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005968 fallbackKeyCode = event.getKeyCode();
5969 } else {
5970 fallbackKeyCode = AKEYCODE_UNKNOWN;
5971 }
5972 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5973 }
5974
5975 ALOG_ASSERT(fallbackKeyCode != -1);
5976
5977 // Cancel the fallback key if the policy decides not to send it anymore.
5978 // We will continue to dispatch the key to the policy but we will no
5979 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005980 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5981 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005982#if DEBUG_OUTBOUND_EVENT_DETAILS
5983 if (fallback) {
5984 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005985 "as a fallback for %d, but on the DOWN it had requested "
5986 "to send %d instead. Fallback canceled.",
5987 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988 } else {
5989 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005990 "but on the DOWN it had requested to send %d. "
5991 "Fallback canceled.",
5992 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 }
5994#endif
5995
5996 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5997 "canceling fallback, policy no longer desires it");
5998 options.keyCode = fallbackKeyCode;
5999 synthesizeCancelationEventsForConnectionLocked(connection, options);
6000
6001 fallback = false;
6002 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006003 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006004 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006005 }
6006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007
6008#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006009 {
6010 std::string msg;
6011 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6012 connection->inputState.getFallbackKeys();
6013 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006014 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006016 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006017 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018 }
6019#endif
6020
6021 if (fallback) {
6022 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006023 keyEntry.eventTime = event.getEventTime();
6024 keyEntry.deviceId = event.getDeviceId();
6025 keyEntry.source = event.getSource();
6026 keyEntry.displayId = event.getDisplayId();
6027 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6028 keyEntry.keyCode = fallbackKeyCode;
6029 keyEntry.scanCode = event.getScanCode();
6030 keyEntry.metaState = event.getMetaState();
6031 keyEntry.repeatCount = event.getRepeatCount();
6032 keyEntry.downTime = event.getDownTime();
6033 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006034
6035#if DEBUG_OUTBOUND_EVENT_DETAILS
6036 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006037 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006038 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006039#endif
6040 return true; // restart the event
6041 } else {
6042#if DEBUG_OUTBOUND_EVENT_DETAILS
6043 ALOGD("Unhandled key event: No fallback key.");
6044#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006045
6046 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006047 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 }
6049 }
6050 return false;
6051}
6052
6053bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006054 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006055 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056 return false;
6057}
6058
6059void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6060 mLock.unlock();
6061
Sean Stoutb4e0a592021-02-23 07:34:53 -08006062 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6063 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064
6065 mLock.lock();
6066}
6067
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068void InputDispatcher::traceInboundQueueLengthLocked() {
6069 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006070 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 }
6072}
6073
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006074void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 if (ATRACE_ENABLED()) {
6076 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006077 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6078 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 }
6080}
6081
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006082void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 if (ATRACE_ENABLED()) {
6084 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006085 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6086 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 }
6088}
6089
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006090void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006091 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006093 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094 dumpDispatchStateLocked(dump);
6095
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006096 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006097 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006098 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 }
6100}
6101
6102void InputDispatcher::monitor() {
6103 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006104 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006106 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107}
6108
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006109/**
6110 * Wake up the dispatcher and wait until it processes all events and commands.
6111 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6112 * this method can be safely called from any thread, as long as you've ensured that
6113 * the work you are interested in completing has already been queued.
6114 */
6115bool InputDispatcher::waitForIdle() {
6116 /**
6117 * Timeout should represent the longest possible time that a device might spend processing
6118 * events and commands.
6119 */
6120 constexpr std::chrono::duration TIMEOUT = 100ms;
6121 std::unique_lock lock(mLock);
6122 mLooper->wake();
6123 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6124 return result == std::cv_status::no_timeout;
6125}
6126
Vishnu Naire798b472020-07-23 13:52:21 -07006127/**
6128 * Sets focus to the window identified by the token. This must be called
6129 * after updating any input window handles.
6130 *
6131 * Params:
6132 * request.token - input channel token used to identify the window that should gain focus.
6133 * request.focusedToken - the token that the caller expects currently to be focused. If the
6134 * specified token does not match the currently focused window, this request will be dropped.
6135 * If the specified focused token matches the currently focused window, the call will succeed.
6136 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6137 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6138 * when requesting the focus change. This determines which request gets
6139 * precedence if there is a focus change request from another source such as pointer down.
6140 */
Vishnu Nair958da932020-08-21 17:12:37 -07006141void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6142 { // acquire lock
6143 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006144 std::optional<FocusResolver::FocusChanges> changes =
6145 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6146 if (changes) {
6147 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006148 }
6149 } // release lock
6150 // Wake up poll loop since it may need to make new input dispatching choices.
6151 mLooper->wake();
6152}
6153
Vishnu Nairc519ff72021-01-21 08:23:08 -08006154void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6155 if (changes.oldFocus) {
6156 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006157 if (focusedInputChannel) {
6158 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6159 "focus left window");
6160 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006161 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006162 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006163 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006164 if (changes.newFocus) {
6165 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006166 }
6167
Prabir Pradhan99987712020-11-10 18:43:05 -08006168 // If a window has pointer capture, then it must have focus. We need to ensure that this
6169 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6170 // If the window loses focus before it loses pointer capture, then the window can be in a state
6171 // where it has pointer capture but not focus, violating the contract. Therefore we must
6172 // dispatch the pointer capture event before the focus event. Since focus events are added to
6173 // the front of the queue (above), we add the pointer capture event to the front of the queue
6174 // after the focus events are added. This ensures the pointer capture event ends up at the
6175 // front.
6176 disablePointerCaptureForcedLocked();
6177
Vishnu Nairc519ff72021-01-21 08:23:08 -08006178 if (mFocusedDisplayId == changes.displayId) {
6179 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006180 }
6181}
Vishnu Nair958da932020-08-21 17:12:37 -07006182
Prabir Pradhan99987712020-11-10 18:43:05 -08006183void InputDispatcher::disablePointerCaptureForcedLocked() {
6184 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6185 return;
6186 }
6187
6188 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6189
6190 if (mFocusedWindowRequestedPointerCapture) {
6191 mFocusedWindowRequestedPointerCapture = false;
6192 setPointerCaptureLocked(false);
6193 }
6194
6195 if (!mWindowTokenWithPointerCapture) {
6196 // No need to send capture changes because no window has capture.
6197 return;
6198 }
6199
6200 if (mPendingEvent != nullptr) {
6201 // Move the pending event to the front of the queue. This will give the chance
6202 // for the pending event to be dropped if it is a captured event.
6203 mInboundQueue.push_front(mPendingEvent);
6204 mPendingEvent = nullptr;
6205 }
6206
6207 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6208 false /* hasCapture */);
6209 mInboundQueue.push_front(std::move(entry));
6210}
6211
Prabir Pradhan99987712020-11-10 18:43:05 -08006212void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6213 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6214 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6215 commandEntry->enabled = enabled;
6216 postCommandLocked(std::move(commandEntry));
6217}
6218
6219void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6220 android::inputdispatcher::CommandEntry* commandEntry) {
6221 mLock.unlock();
6222
6223 mPolicy->setPointerCapture(commandEntry->enabled);
6224
6225 mLock.lock();
6226}
6227
Vishnu Nair599f1412021-06-21 10:39:58 -07006228void InputDispatcher::displayRemoved(int32_t displayId) {
6229 { // acquire lock
6230 std::scoped_lock _l(mLock);
6231 // Set an empty list to remove all handles from the specific display.
6232 setInputWindowsLocked(/* window handles */ {}, displayId);
6233 setFocusedApplicationLocked(displayId, nullptr);
6234 // Call focus resolver to clean up stale requests. This must be called after input windows
6235 // have been removed for the removed display.
6236 mFocusResolver.displayRemoved(displayId);
6237 } // release lock
6238
6239 // Wake up poll loop since it may need to make new input dispatching choices.
6240 mLooper->wake();
6241}
6242
chaviw15fab6f2021-06-07 14:15:52 -05006243void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6244 // The listener sends the windows as a flattened array. Separate the windows by display for
6245 // more convenient parsing.
6246 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6247
6248 for (const auto& info : windowInfos) {
6249 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6250 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6251 }
6252 setInputWindows(handlesPerDisplay);
6253}
6254
Garfield Tane84e6f92019-08-29 17:28:41 -07006255} // namespace android::inputdispatcher