blob: 9f4108dc4fd655f79e795a619c226e2837d5d5fd [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>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080058#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080081using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000082using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080083using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050084using android::gui::FocusRequest;
85using android::gui::TouchOcclusionMode;
86using android::gui::WindowInfo;
87using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080088using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100089using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080090using android::os::InputEventInjectionResult;
91using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100092using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080093
Garfield Tane84e6f92019-08-29 17:28:41 -070094namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Prabir Pradhan93a0f912021-04-21 13:47:42 -070096// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
97// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
98static bool isPerWindowInputRotationEnabled() {
99 static const bool PER_WINDOW_INPUT_ROTATION =
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700100 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
101
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700102 return PER_WINDOW_INPUT_ROTATION;
103}
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Default input dispatching timeout if there is no focused application or paused window
106// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800107const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
108 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
109 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
111// Amount of time to allow for all pending events to be processed when an app switch
112// key is on the way. This is used to preempt input dispatch and drop input events
113// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000114constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115
116// Amount of time to allow for an event to be dispatched (measured since its eventTime)
117// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000118constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120// 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 +0000121constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
122
123// Log a warning when an interception call takes longer than this to process.
124constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700126// Additional key latency in case a connection is still processing some motion events.
127// This will help with the case when a user touched a button that opens a new window,
128// and gives us the chance to dispatch the key to this new window.
129constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
130
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000132constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
133
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000134// Event log tags. See EventLogTags.logtags for reference
135constexpr int LOGTAG_INPUT_INTERACTION = 62000;
136constexpr int LOGTAG_INPUT_FOCUS = 62001;
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138static inline nsecs_t now() {
139 return systemTime(SYSTEM_TIME_MONOTONIC);
140}
141
142static inline const char* toString(bool value) {
143 return value ? "true" : "false";
144}
145
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000146static inline const std::string toString(sp<IBinder> binder) {
147 if (binder == nullptr) {
148 return "<null>";
149 }
150 return StringPrintf("%p", binder.get());
151}
152
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
155 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156}
157
158static bool isValidKeyAction(int32_t action) {
159 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 case AKEY_EVENT_ACTION_DOWN:
161 case AKEY_EVENT_ACTION_UP:
162 return true;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
168static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170 ALOGE("Key event has invalid action code 0x%x", action);
171 return false;
172 }
173 return true;
174}
175
Michael Wright7b159c92015-05-14 14:48:03 +0100176static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_DOWN:
179 case AMOTION_EVENT_ACTION_UP:
180 case AMOTION_EVENT_ACTION_CANCEL:
181 case AMOTION_EVENT_ACTION_MOVE:
182 case AMOTION_EVENT_ACTION_OUTSIDE:
183 case AMOTION_EVENT_ACTION_HOVER_ENTER:
184 case AMOTION_EVENT_ACTION_HOVER_MOVE:
185 case AMOTION_EVENT_ACTION_HOVER_EXIT:
186 case AMOTION_EVENT_ACTION_SCROLL:
187 return true;
188 case AMOTION_EVENT_ACTION_POINTER_DOWN:
189 case AMOTION_EVENT_ACTION_POINTER_UP: {
190 int32_t index = getMotionEventActionPointerIndex(action);
191 return index >= 0 && index < pointerCount;
192 }
193 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
194 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
195 return actionButton != 0;
196 default:
197 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 }
199}
200
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500201static int64_t millis(std::chrono::nanoseconds t) {
202 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
203}
204
Michael Wright7b159c92015-05-14 14:48:03 +0100205static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700206 const PointerProperties* pointerProperties) {
207 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 ALOGE("Motion event has invalid action code 0x%x", action);
209 return false;
210 }
211 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000212 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700213 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 return false;
215 }
216 BitSet32 pointerIdBits;
217 for (size_t i = 0; i < pointerCount; i++) {
218 int32_t id = pointerProperties[i].id;
219 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700220 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
221 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return false;
223 }
224 if (pointerIdBits.hasBit(id)) {
225 ALOGE("Motion event has duplicate pointer id %d", id);
226 return false;
227 }
228 pointerIdBits.markBit(id);
229 }
230 return true;
231}
232
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000233static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000235 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 }
237
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000238 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 bool first = true;
240 Region::const_iterator cur = region.begin();
241 Region::const_iterator const tail = region.end();
242 while (cur != tail) {
243 if (first) {
244 first = false;
245 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800246 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800248 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 cur++;
250 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000251 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252}
253
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500254static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
255 constexpr size_t maxEntries = 50; // max events to print
256 constexpr size_t skipBegin = maxEntries / 2;
257 const size_t skipEnd = queue.size() - maxEntries / 2;
258 // skip from maxEntries / 2 ... size() - maxEntries/2
259 // only print from 0 .. skipBegin and then from skipEnd .. size()
260
261 std::string dump;
262 for (size_t i = 0; i < queue.size(); i++) {
263 const DispatchEntry& entry = *queue[i];
264 if (i >= skipBegin && i < skipEnd) {
265 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
266 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
267 continue;
268 }
269 dump.append(INDENT4);
270 dump += entry.eventEntry->getDescription();
271 dump += StringPrintf(", seq=%" PRIu32
272 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
273 entry.seq, entry.targetFlags, entry.resolvedAction,
274 ns2ms(currentTime - entry.eventEntry->eventTime));
275 if (entry.deliveryTime != 0) {
276 // This entry was delivered, so add information on how long we've been waiting
277 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
278 }
279 dump.append("\n");
280 }
281 return dump;
282}
283
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700284/**
285 * Find the entry in std::unordered_map by key, and return it.
286 * If the entry is not found, return a default constructed entry.
287 *
288 * Useful when the entries are vectors, since an empty vector will be returned
289 * if the entry is not found.
290 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
291 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700292template <typename K, typename V>
293static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700294 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700295 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800296}
297
chaviw3277faf2021-05-19 16:45:23 -0500298static bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700299 if (first == second) {
300 return true;
301 }
302
303 if (first == nullptr || second == nullptr) {
304 return false;
305 }
306
307 return first->getToken() == second->getToken();
308}
309
chaviw3277faf2021-05-19 16:45:23 -0500310static bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000311 if (first == nullptr || second == nullptr) {
312 return false;
313 }
314 return first->applicationInfo.token != nullptr &&
315 first->applicationInfo.token == second->applicationInfo.token;
316}
317
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800318static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
319 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
320}
321
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000322static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700323 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000324 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900325 if (eventEntry->type == EventEntry::Type::MOTION) {
326 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700327 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
328 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900329 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700330 // Use identity transform for joystick and position-based (touchpad) events because they
331 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900332 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700333 1.0f /*globalScaleFactor*/,
Evan Rosky09576692021-07-01 12:22:09 -0700334 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700335 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900336 }
337 }
338
chaviw1ff3d1e2020-07-01 15:53:47 -0700339 if (inputTarget.useDefaultPointerTransform()) {
340 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700341 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700342 inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700343 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700344 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345 }
346
347 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
348 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700350 std::vector<PointerCoords> pointerCoords;
351 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352
353 // Use the first pointer information to normalize all other pointers. This could be any pointer
354 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 // uses the transform for the normalized pointer.
356 const ui::Transform& firstPointerTransform =
357 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
358 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 // Iterate through all pointers in the event to normalize against the first.
361 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
362 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
363 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700364 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 // First, apply the current pointer's transform to update the coordinates into
368 // window space.
369 pointerCoords[pointerIndex].transform(currTransform);
370 // Next, apply the inverse transform of the normalized coordinates so the
371 // current coordinates are transformed into the normalized coordinate space.
372 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000373 }
374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700375 std::unique_ptr<MotionEntry> combinedMotionEntry =
376 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
377 motionEntry.deviceId, motionEntry.source,
378 motionEntry.displayId, motionEntry.policyFlags,
379 motionEntry.action, motionEntry.actionButton,
380 motionEntry.flags, motionEntry.metaState,
381 motionEntry.buttonState, motionEntry.classification,
382 motionEntry.edgeFlags, motionEntry.xPrecision,
383 motionEntry.yPrecision, motionEntry.xCursorPosition,
384 motionEntry.yCursorPosition, motionEntry.downTime,
385 motionEntry.pointerCount, motionEntry.pointerProperties,
386 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387
388 if (motionEntry.injectionState) {
389 combinedMotionEntry->injectionState = motionEntry.injectionState;
390 combinedMotionEntry->injectionState->refCount += 1;
391 }
392
393 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700394 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700395 firstPointerTransform, inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700396 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700397 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398 return dispatchEntry;
399}
400
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700401static void addGestureMonitors(const std::vector<Monitor>& monitors,
402 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
403 float yOffset = 0) {
404 if (monitors.empty()) {
405 return;
406 }
407 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
408 for (const Monitor& monitor : monitors) {
409 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
410 }
411}
412
Garfield Tan15601662020-09-22 15:32:38 -0700413static status_t openInputChannelPair(const std::string& name,
414 std::shared_ptr<InputChannel>& serverChannel,
415 std::unique_ptr<InputChannel>& clientChannel) {
416 std::unique_ptr<InputChannel> uniqueServerChannel;
417 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
418
419 serverChannel = std::move(uniqueServerChannel);
420 return result;
421}
422
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500423template <typename T>
424static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
425 if (lhs == nullptr && rhs == nullptr) {
426 return true;
427 }
428 if (lhs == nullptr || rhs == nullptr) {
429 return false;
430 }
431 return *lhs == *rhs;
432}
433
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000434static sp<IPlatformCompatNative> getCompatService() {
435 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
436 if (service == nullptr) {
437 ALOGE("Failed to link to compat service");
438 return nullptr;
439 }
440 return interface_cast<IPlatformCompatNative>(service);
441}
442
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000443static KeyEvent createKeyEvent(const KeyEntry& entry) {
444 KeyEvent event;
445 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
446 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
447 entry.repeatCount, entry.downTime, entry.eventTime);
448 return event;
449}
450
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000451static std::optional<int32_t> findMonitorPidByToken(
452 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
453 const sp<IBinder>& token) {
454 for (const auto& it : monitorsByDisplay) {
455 const std::vector<Monitor>& monitors = it.second;
456 for (const Monitor& monitor : monitors) {
457 if (monitor.inputChannel->getConnectionToken() == token) {
458 return monitor.pid;
459 }
460 }
461 }
462 return std::nullopt;
463}
464
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000465static bool shouldReportMetricsForConnection(const Connection& connection) {
466 // Do not keep track of gesture monitors. They receive every event and would disproportionately
467 // affect the statistics.
468 if (connection.monitor) {
469 return false;
470 }
471 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
472 if (!connection.responsive) {
473 return false;
474 }
475 return true;
476}
477
478static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
479 const Connection& connection) {
480 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
481 const int32_t& inputEventId = eventEntry.id;
482 if (inputEventId != dispatchEntry.resolvedEventId) {
483 // Event was transmuted
484 return false;
485 }
486 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
487 return false;
488 }
489 // Only track latency for events that originated from hardware
490 if (eventEntry.isSynthesized()) {
491 return false;
492 }
493 const EventEntry::Type& inputEventEntryType = eventEntry.type;
494 if (inputEventEntryType == EventEntry::Type::KEY) {
495 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
496 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
497 return false;
498 }
499 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
500 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
501 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
502 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
503 return false;
504 }
505 } else {
506 // Not a key or a motion
507 return false;
508 }
509 if (!shouldReportMetricsForConnection(connection)) {
510 return false;
511 }
512 return true;
513}
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515// --- InputDispatcher ---
516
Garfield Tan00f511d2019-06-12 16:55:40 -0700517InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
518 : mPolicy(policy),
519 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700520 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800521 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700522 mAppSwitchSawKeyDown(false),
523 mAppSwitchDueTime(LONG_LONG_MAX),
524 mNextUnblockedEvent(nullptr),
525 mDispatchEnabled(false),
526 mDispatchFrozen(false),
527 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800528 // mInTouchMode will be initialized by the WindowManager to the default device config.
529 // To avoid leaking stack in case that call never comes, and for tests,
530 // initialize it here anyways.
531 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100532 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000533 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800534 mFocusedWindowRequestedPointerCapture(false),
535 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000536 mLatencyAggregator(),
537 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000538 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800540 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541
Yi Kong9b14ac62018-07-17 13:48:38 -0700542 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543
544 policy->getDispatcherConfiguration(&mConfig);
545}
546
547InputDispatcher::~InputDispatcher() {
548 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800549 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550
551 resetKeyRepeatLocked();
552 releasePendingEventLocked();
553 drainInboundQueueLocked();
554 }
555
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000556 while (!mConnectionsByToken.empty()) {
557 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700558 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 }
560}
561
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700562status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700563 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700564 return ALREADY_EXISTS;
565 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700566 mThread = std::make_unique<InputThread>(
567 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
568 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700569}
570
571status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700572 if (mThread && mThread->isCallingThread()) {
573 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700574 return INVALID_OPERATION;
575 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700576 mThread.reset();
577 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700578}
579
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580void InputDispatcher::dispatchOnce() {
581 nsecs_t nextWakeupTime = LONG_LONG_MAX;
582 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800583 std::scoped_lock _l(mLock);
584 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585
586 // Run a dispatch loop if there are no pending commands.
587 // The dispatch loop might enqueue commands to run afterwards.
588 if (!haveCommandsLocked()) {
589 dispatchOnceInnerLocked(&nextWakeupTime);
590 }
591
592 // Run all pending commands if there are any.
593 // If any commands were run then force the next poll to wake up immediately.
594 if (runCommandsLockedInterruptible()) {
595 nextWakeupTime = LONG_LONG_MIN;
596 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800597
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700598 // If we are still waiting for ack on some events,
599 // we might have to wake up earlier to check if an app is anr'ing.
600 const nsecs_t nextAnrCheck = processAnrsLocked();
601 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
602
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800603 // We are about to enter an infinitely long sleep, because we have no commands or
604 // pending or queued events
605 if (nextWakeupTime == LONG_LONG_MAX) {
606 mDispatcherEnteredIdle.notify_all();
607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 } // release lock
609
610 // Wait for callback or timeout or wake. (make sure we round up, not down)
611 nsecs_t currentTime = now();
612 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
613 mLooper->pollOnce(timeoutMillis);
614}
615
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700616/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500617 * Raise ANR if there is no focused window.
618 * Before the ANR is raised, do a final state check:
619 * 1. The currently focused application must be the same one we are waiting for.
620 * 2. Ensure we still don't have a focused window.
621 */
622void InputDispatcher::processNoFocusedWindowAnrLocked() {
623 // Check if the application that we are waiting for is still focused.
624 std::shared_ptr<InputApplicationHandle> focusedApplication =
625 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
626 if (focusedApplication == nullptr ||
627 focusedApplication->getApplicationToken() !=
628 mAwaitedFocusedApplication->getApplicationToken()) {
629 // Unexpected because we should have reset the ANR timer when focused application changed
630 ALOGE("Waited for a focused window, but focused application has already changed to %s",
631 focusedApplication->getName().c_str());
632 return; // The focused application has changed.
633 }
634
chaviw3277faf2021-05-19 16:45:23 -0500635 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500636 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
637 if (focusedWindowHandle != nullptr) {
638 return; // We now have a focused window. No need for ANR.
639 }
640 onAnrLocked(mAwaitedFocusedApplication);
641}
642
643/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700644 * Check if any of the connections' wait queues have events that are too old.
645 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
646 * Return the time at which we should wake up next.
647 */
648nsecs_t InputDispatcher::processAnrsLocked() {
649 const nsecs_t currentTime = now();
650 nsecs_t nextAnrCheck = LONG_LONG_MAX;
651 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
652 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
653 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500654 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700655 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500656 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700657 return LONG_LONG_MIN;
658 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500659 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700660 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
661 }
662 }
663
664 // Check if any connection ANRs are due
665 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
666 if (currentTime < nextAnrCheck) { // most likely scenario
667 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
668 }
669
670 // If we reached here, we have an unresponsive connection.
671 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
672 if (connection == nullptr) {
673 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
674 return nextAnrCheck;
675 }
676 connection->responsive = false;
677 // Stop waking up for this unresponsive connection
678 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000679 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700680 return LONG_LONG_MIN;
681}
682
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500683std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw3277faf2021-05-19 16:45:23 -0500684 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700685 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500686 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700687 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500688 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689}
690
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
692 nsecs_t currentTime = now();
693
Jeff Browndc5992e2014-04-11 01:27:26 -0700694 // Reset the key repeat timer whenever normal dispatch is suspended while the
695 // device is in a non-interactive state. This is to ensure that we abort a key
696 // repeat if the device is just coming out of sleep.
697 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 resetKeyRepeatLocked();
699 }
700
701 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
702 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100703 if (DEBUG_FOCUS) {
704 ALOGD("Dispatch frozen. Waiting some more.");
705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 return;
707 }
708
709 // Optimize latency of app switches.
710 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
711 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
712 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
713 if (mAppSwitchDueTime < *nextWakeupTime) {
714 *nextWakeupTime = mAppSwitchDueTime;
715 }
716
717 // Ready to start a new event.
718 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700719 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700720 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 if (isAppSwitchDue) {
722 // The inbound queue is empty so the app switch key we were waiting
723 // for will never arrive. Stop waiting for it.
724 resetPendingAppSwitchLocked(false);
725 isAppSwitchDue = false;
726 }
727
728 // Synthesize a key repeat if appropriate.
729 if (mKeyRepeatState.lastKeyEntry) {
730 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
731 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
732 } else {
733 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
734 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
735 }
736 }
737 }
738
739 // Nothing to do if there is no pending event.
740 if (!mPendingEvent) {
741 return;
742 }
743 } else {
744 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700745 mPendingEvent = mInboundQueue.front();
746 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 traceInboundQueueLengthLocked();
748 }
749
750 // Poke user activity for this event.
751 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700752 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 }
755
756 // Now we have an event to dispatch.
757 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700758 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700760 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700762 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700764 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 }
766
767 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700768 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 }
770
771 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700773 const ConfigurationChangedEntry& typedEntry =
774 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700776 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700780 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700781 const DeviceResetEntry& typedEntry =
782 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700783 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700784 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 break;
786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100788 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700789 std::shared_ptr<FocusEntry> typedEntry =
790 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100791 dispatchFocusLocked(currentTime, typedEntry);
792 done = true;
793 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
794 break;
795 }
796
Prabir Pradhan99987712020-11-10 18:43:05 -0800797 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
798 const auto typedEntry =
799 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
800 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
801 done = true;
802 break;
803 }
804
arthurhungb89ccb02020-12-30 16:19:01 +0800805 case EventEntry::Type::DRAG: {
806 std::shared_ptr<DragEntry> typedEntry =
807 std::static_pointer_cast<DragEntry>(mPendingEvent);
808 dispatchDragLocked(currentTime, typedEntry);
809 done = true;
810 break;
811 }
812
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700813 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700814 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700816 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 resetPendingAppSwitchLocked(true);
818 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700819 } else if (dropReason == DropReason::NOT_DROPPED) {
820 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700821 }
822 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700824 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700826 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
827 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700829 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 break;
831 }
832
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700833 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700834 std::shared_ptr<MotionEntry> motionEntry =
835 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700836 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
837 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700840 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700841 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700842 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
843 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700844 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700845 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 }
Chris Yef59a2f42020-10-16 12:55:26 -0700848
849 case EventEntry::Type::SENSOR: {
850 std::shared_ptr<SensorEntry> sensorEntry =
851 std::static_pointer_cast<SensorEntry>(mPendingEvent);
852 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
853 dropReason = DropReason::APP_SWITCH;
854 }
855 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
856 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
857 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
858 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
859 dropReason = DropReason::STALE;
860 }
861 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
862 done = true;
863 break;
864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
866
867 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700869 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
Michael Wright3a981722015-06-10 15:26:13 +0100871 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872
873 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
876}
877
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700878/**
879 * Return true if the events preceding this incoming motion event should be dropped
880 * Return false otherwise (the default behaviour)
881 */
882bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700883 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700884 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700885
886 // Optimize case where the current application is unresponsive and the user
887 // decides to touch a window in a different application.
888 // If the application takes too long to catch up then we drop all events preceding
889 // the touch into the other window.
890 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700891 int32_t displayId = motionEntry.displayId;
892 int32_t x = static_cast<int32_t>(
893 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
894 int32_t y = static_cast<int32_t>(
895 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw3277faf2021-05-19 16:45:23 -0500896 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700897 findTouchedWindowAtLocked(displayId, x, y, nullptr);
898 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 touchedWindowHandle->getApplicationToken() !=
900 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700901 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700902 ALOGI("Pruning input queue because user touched a different application while waiting "
903 "for %s",
904 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700905 return true;
906 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907
908 // Alternatively, maybe there's a gesture monitor that could handle this event
909 std::vector<TouchedMonitor> gestureMonitors =
910 findTouchedGestureMonitorsLocked(displayId, {});
911 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
912 sp<Connection> connection =
913 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000914 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700915 // This monitor could take more input. Drop all events preceding this
916 // event, so that gesture monitor could get a chance to receive the stream
917 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
918 "responsive gesture monitor that may handle the event",
919 mAwaitedFocusedApplication->getName().c_str());
920 return true;
921 }
922 }
923 }
924
925 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
926 // yet been processed by some connections, the dispatcher will wait for these motion
927 // events to be processed before dispatching the key event. This is because these motion events
928 // may cause a new window to be launched, which the user might expect to receive focus.
929 // To prevent waiting forever for such events, just send the key to the currently focused window
930 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
931 ALOGD("Received a new pointer down event, stop waiting for events to process and "
932 "just send the pending key event to the focused window.");
933 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700934 }
935 return false;
936}
937
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700938bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700939 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700940 mInboundQueue.push_back(std::move(newEntry));
941 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 traceInboundQueueLengthLocked();
943
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700944 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700945 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 // Optimize app switch latency.
947 // If the application takes too long to catch up then we drop all events preceding
948 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700949 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700951 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700953 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700958 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 mAppSwitchSawKeyDown = false;
960 needWake = true;
961 }
962 }
963 }
964 break;
965 }
966
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700967 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700968 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
969 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700970 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100974 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700975 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
976 break;
977 }
978 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800979 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700980 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800981 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
982 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700983 // nothing to do
984 break;
985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 }
987
988 return needWake;
989}
990
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700992 // Do not store sensor event in recent queue to avoid flooding the queue.
993 if (entry->type != EventEntry::Type::SENSOR) {
994 mRecentQueue.push_back(entry);
995 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700996 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700997 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
999}
1000
chaviw3277faf2021-05-19 16:45:23 -05001001sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1002 int32_t y, TouchState* touchState,
1003 bool addOutsideTargets,
1004 bool addPortalWindows,
1005 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001006 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
1007 LOG_ALWAYS_FATAL(
1008 "Must provide a valid touch state if adding portal windows or outside targets");
1009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 // Traverse windows from front to back to find touched window.
chaviw3277faf2021-05-19 16:45:23 -05001011 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1012 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001013 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001014 continue;
1015 }
chaviw3277faf2021-05-19 16:45:23 -05001016 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001018 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019
1020 if (windowInfo->visible) {
chaviw3277faf2021-05-19 16:45:23 -05001021 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1022 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1023 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001025 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1027 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001028 if (addPortalWindows) {
1029 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001030 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001031 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001032 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 // Found window.
1036 return windowHandle;
1037 }
1038 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001039
chaviw3277faf2021-05-19 16:45:23 -05001040 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001041 touchState->addOrUpdateWindow(windowHandle,
1042 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1043 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
1047 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001048 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049}
1050
Garfield Tane84e6f92019-08-29 17:28:41 -07001051std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
chaviw3277faf2021-05-19 16:45:23 -05001052 int32_t displayId, const std::vector<sp<WindowInfoHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001053 std::vector<TouchedMonitor> touchedMonitors;
1054
1055 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1056 addGestureMonitors(monitors, touchedMonitors);
chaviw3277faf2021-05-19 16:45:23 -05001057 for (const sp<WindowInfoHandle>& portalWindow : portalWindows) {
1058 const WindowInfo* windowInfo = portalWindow->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001059 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1061 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001062 }
1063 return touchedMonitors;
1064}
1065
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001066void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 const char* reason;
1068 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001069 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 reason = "inbound event was dropped because the policy consumed it";
1074 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001075 case DropReason::DISABLED:
1076 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 ALOGI("Dropped event because input dispatch is disabled.");
1078 }
1079 reason = "inbound event was dropped because input dispatch is disabled";
1080 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 ALOGI("Dropped event because of pending overdue app switch.");
1083 reason = "inbound event was dropped because of pending overdue app switch";
1084 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001085 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 ALOGI("Dropped event because the current application is not responding and the user "
1087 "has started interacting with a different application.");
1088 reason = "inbound event was dropped because the current application is not responding "
1089 "and the user has started interacting with a different application";
1090 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 ALOGI("Dropped event because it is stale.");
1093 reason = "inbound event was dropped because it is stale";
1094 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001095 case DropReason::NO_POINTER_CAPTURE:
1096 ALOGI("Dropped event because there is no window with Pointer Capture.");
1097 reason = "inbound event was dropped because there is no window with Pointer Capture";
1098 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 case DropReason::NOT_DROPPED: {
1100 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 }
1104
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001105 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001106 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1108 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001109 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001111 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001112 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1113 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1115 synthesizeCancelationEventsForAllConnectionsLocked(options);
1116 } else {
1117 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1118 synthesizeCancelationEventsForAllConnectionsLocked(options);
1119 }
1120 break;
1121 }
Chris Yef59a2f42020-10-16 12:55:26 -07001122 case EventEntry::Type::SENSOR: {
1123 break;
1124 }
arthurhungb89ccb02020-12-30 16:19:01 +08001125 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1126 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001127 break;
1128 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001129 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001130 case EventEntry::Type::CONFIGURATION_CHANGED:
1131 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001132 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 break;
1134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 }
1136}
1137
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001138static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1140 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141}
1142
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001143bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1144 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1145 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1146 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147}
1148
1149bool InputDispatcher::isAppSwitchPendingLocked() {
1150 return mAppSwitchDueTime != LONG_LONG_MAX;
1151}
1152
1153void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1154 mAppSwitchDueTime = LONG_LONG_MAX;
1155
1156#if DEBUG_APP_SWITCH
1157 if (handled) {
1158 ALOGD("App switch has arrived.");
1159 } else {
1160 ALOGD("App switch was abandoned.");
1161 }
1162#endif
1163}
1164
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001166 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167}
1168
1169bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001170 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 return false;
1172 }
1173
1174 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001175 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001176 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001178 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179
1180 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001181 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 return true;
1183}
1184
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001185void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1186 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187}
1188
1189void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001190 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001191 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 releaseInboundEventLocked(entry);
1194 }
1195 traceInboundQueueLengthLocked();
1196}
1197
1198void InputDispatcher::releasePendingEventLocked() {
1199 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001201 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
1203}
1204
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001205void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001207 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208#if DEBUG_DISPATCH_CYCLE
1209 ALOGD("Injected inbound event was dropped.");
1210#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001211 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001214 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 }
1216 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217}
1218
1219void InputDispatcher::resetKeyRepeatLocked() {
1220 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001221 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223}
1224
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1226 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227
Michael Wright2e732952014-09-24 13:26:59 -07001228 uint32_t policyFlags = entry->policyFlags &
1229 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231 std::shared_ptr<KeyEntry> newEntry =
1232 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1233 entry->source, entry->displayId, policyFlags, entry->action,
1234 entry->flags, entry->keyCode, entry->scanCode,
1235 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 newEntry->syntheticRepeat = true;
1238 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001240 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241}
1242
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247#endif
1248
1249 // Reset key repeating in case a keyboard device was added or removed or something.
1250 resetKeyRepeatLocked();
1251
1252 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001253 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1254 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001256 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 return true;
1258}
1259
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1261 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001263 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1264 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265#endif
1266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001267 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 synthesizeCancelationEventsForAllConnectionsLocked(options);
1270 return true;
1271}
1272
Vishnu Nairad321cd2020-08-20 16:40:21 -07001273void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001274 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001275 if (mPendingEvent != nullptr) {
1276 // Move the pending event to the front of the queue. This will give the chance
1277 // for the pending event to get dispatched to the newly focused window
1278 mInboundQueue.push_front(mPendingEvent);
1279 mPendingEvent = nullptr;
1280 }
1281
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282 std::unique_ptr<FocusEntry> focusEntry =
1283 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1284 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001285
1286 // This event should go to the front of the queue, but behind all other focus events
1287 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001288 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001289 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 [](const std::shared_ptr<EventEntry>& event) {
1291 return event->type == EventEntry::Type::FOCUS;
1292 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001293
1294 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001296}
1297
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001298void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001299 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001300 if (channel == nullptr) {
1301 return; // Window has gone away
1302 }
1303 InputTarget target;
1304 target.inputChannel = channel;
1305 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1306 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001307 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1308 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001309 std::string reason = std::string("reason=").append(entry->reason);
1310 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001311 dispatchEventLocked(currentTime, entry, {target});
1312}
1313
Prabir Pradhan99987712020-11-10 18:43:05 -08001314void InputDispatcher::dispatchPointerCaptureChangedLocked(
1315 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1316 DropReason& dropReason) {
1317 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001318 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1319 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1320 }
1321 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001322 // Pointer capture was already forcefully disabled because of focus change.
1323 dropReason = DropReason::NOT_DROPPED;
1324 return;
1325 }
1326
1327 // Set drop reason for early returns
1328 dropReason = DropReason::NO_POINTER_CAPTURE;
1329
1330 sp<IBinder> token;
1331 if (entry->pointerCaptureEnabled) {
1332 // Enable Pointer Capture
1333 if (!mFocusedWindowRequestedPointerCapture) {
1334 // This can happen if a window requests capture and immediately releases capture.
1335 ALOGW("No window requested Pointer Capture.");
1336 return;
1337 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001338 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001339 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1340 mWindowTokenWithPointerCapture = token;
1341 } else {
1342 // Disable Pointer Capture
1343 token = mWindowTokenWithPointerCapture;
1344 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001345 if (mFocusedWindowRequestedPointerCapture) {
1346 mFocusedWindowRequestedPointerCapture = false;
1347 setPointerCaptureLocked(false);
1348 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001349 }
1350
1351 auto channel = getInputChannelLocked(token);
1352 if (channel == nullptr) {
1353 // Window has gone away, clean up Pointer Capture state.
1354 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001355 if (mFocusedWindowRequestedPointerCapture) {
1356 mFocusedWindowRequestedPointerCapture = false;
1357 setPointerCaptureLocked(false);
1358 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001359 return;
1360 }
1361 InputTarget target;
1362 target.inputChannel = channel;
1363 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1364 entry->dispatchInProgress = true;
1365 dispatchEventLocked(currentTime, entry, {target});
1366
1367 dropReason = DropReason::NOT_DROPPED;
1368}
1369
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001370bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001371 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373 if (!entry->dispatchInProgress) {
1374 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1375 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1376 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1377 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001378 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 // We have seen two identical key downs in a row which indicates that the device
1380 // driver is automatically generating key repeats itself. We take note of the
1381 // repeat here, but we disable our own next key repeat timer since it is clear that
1382 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001383 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1384 // Make sure we don't get key down from a different device. If a different
1385 // device Id has same key pressed down, the new device Id will replace the
1386 // current one to hold the key repeat with repeat count reset.
1387 // In the future when got a KEY_UP on the device id, drop it and do not
1388 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1390 resetKeyRepeatLocked();
1391 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1392 } else {
1393 // Not a repeat. Save key down state in case we do see a repeat later.
1394 resetKeyRepeatLocked();
1395 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1396 }
1397 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001398 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1399 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001400 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001401#if DEBUG_INBOUND_EVENT_DETAILS
1402 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1403#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 resetKeyRepeatLocked();
1406 }
1407
1408 if (entry->repeatCount == 1) {
1409 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1410 } else {
1411 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1412 }
1413
1414 entry->dispatchInProgress = true;
1415
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001416 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 }
1418
1419 // Handle case where the policy asked us to try again later last time.
1420 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1421 if (currentTime < entry->interceptKeyWakeupTime) {
1422 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1423 *nextWakeupTime = entry->interceptKeyWakeupTime;
1424 }
1425 return false; // wait until next wakeup
1426 }
1427 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1428 entry->interceptKeyWakeupTime = 0;
1429 }
1430
1431 // Give the policy a chance to intercept the key.
1432 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1433 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001434 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001435 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001436 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001437 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001438 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001440 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 return false; // wait for the command to run
1442 } else {
1443 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1444 }
1445 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001446 if (*dropReason == DropReason::NOT_DROPPED) {
1447 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 }
1449 }
1450
1451 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001452 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001453 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001454 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1455 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001456 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 return true;
1458 }
1459
1460 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001461 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001462 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001463 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001464 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 return false;
1466 }
1467
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001468 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001469 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 return true;
1471 }
1472
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001473 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001474 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475
1476 // Dispatch the key.
1477 dispatchEventLocked(currentTime, entry, inputTargets);
1478 return true;
1479}
1480
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001481void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001483 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001484 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1485 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001486 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1487 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1488 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489#endif
1490}
1491
Chris Yef59a2f42020-10-16 12:55:26 -07001492void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1493 mLock.unlock();
1494
1495 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1496 if (entry->accuracyChanged) {
1497 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1498 }
1499 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1500 entry->hwTimestamp, entry->values);
1501 mLock.lock();
1502}
1503
1504void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1505 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1506#if DEBUG_OUTBOUND_EVENT_DETAILS
1507 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1508 "source=0x%x, sensorType=%s",
1509 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001510 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001511#endif
1512 std::unique_ptr<CommandEntry> commandEntry =
1513 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1514 commandEntry->sensorEntry = entry;
1515 postCommandLocked(std::move(commandEntry));
1516}
1517
1518bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1519#if DEBUG_OUTBOUND_EVENT_DETAILS
1520 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1521 NamedEnum::string(sensorType).c_str());
1522#endif
1523 { // acquire lock
1524 std::scoped_lock _l(mLock);
1525
1526 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1527 std::shared_ptr<EventEntry> entry = *it;
1528 if (entry->type == EventEntry::Type::SENSOR) {
1529 it = mInboundQueue.erase(it);
1530 releaseInboundEventLocked(entry);
1531 }
1532 }
1533 }
1534 return true;
1535}
1536
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001537bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001538 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001539 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001541 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 entry->dispatchInProgress = true;
1543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001544 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546
1547 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001548 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001550 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1551 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 return true;
1553 }
1554
1555 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1556
1557 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001558 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559
1560 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001561 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 if (isPointerEvent) {
1563 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001565 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001566 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 } else {
1568 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001570 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001572 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 return false;
1574 }
1575
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001576 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001578 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1579 return true;
1580 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001582 CancelationOptions::Mode mode(isPointerEvent
1583 ? CancelationOptions::CANCEL_POINTER_EVENTS
1584 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1585 CancelationOptions options(mode, "input event injection failed");
1586 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 return true;
1588 }
1589
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001590 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001591 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001593 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001594 std::unordered_map<int32_t, TouchState>::iterator it =
1595 mTouchStatesByDisplay.find(entry->displayId);
1596 if (it != mTouchStatesByDisplay.end()) {
1597 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001598 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001599 // The event has gone through these portal windows, so we add monitoring targets of
1600 // the corresponding displays as well.
1601 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05001602 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001603 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001604 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001605 }
1606 }
1607 }
1608 }
1609
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 // Dispatch the motion.
1611 if (conflictingPointerActions) {
1612 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001613 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 synthesizeCancelationEventsForAllConnectionsLocked(options);
1615 }
1616 dispatchEventLocked(currentTime, entry, inputTargets);
1617 return true;
1618}
1619
chaviw3277faf2021-05-19 16:45:23 -05001620void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001621 bool isExiting, const MotionEntry& motionEntry) {
1622 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1623 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1624 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1625 PointerCoords pointerCoords;
1626 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1627 pointerCoords.transform(windowHandle->getInfo()->transform);
1628
1629 std::unique_ptr<DragEntry> dragEntry =
1630 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1631 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1632 pointerCoords.getY());
1633
1634 enqueueInboundEventLocked(std::move(dragEntry));
1635}
1636
1637void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1638 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1639 if (channel == nullptr) {
1640 return; // Window has gone away
1641 }
1642 InputTarget target;
1643 target.inputChannel = channel;
1644 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1645 entry->dispatchInProgress = true;
1646 dispatchEventLocked(currentTime, entry, {target});
1647}
1648
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001651 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 ", policyFlags=0x%x, "
1653 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1654 "metaState=0x%x, buttonState=0x%x,"
1655 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001656 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1657 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1658 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001660 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 "x=%f, y=%f, pressure=%f, size=%f, "
1663 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1664 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001665 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1666 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1667 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1668 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1669 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1670 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1671 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1672 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1673 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1674 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 }
1676#endif
1677}
1678
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001679void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1680 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001681 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001682 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683#if DEBUG_DISPATCH_CYCLE
1684 ALOGD("dispatchEventToCurrentInputTargets");
1685#endif
1686
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001687 updateInteractionTokensLocked(*eventEntry, inputTargets);
1688
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1690
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001691 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001693 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001694 sp<Connection> connection =
1695 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001696 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001697 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001699 if (DEBUG_FOCUS) {
1700 ALOGD("Dropping event delivery to target with channel '%s' because it "
1701 "is no longer registered with the input dispatcher.",
1702 inputTarget.inputChannel->getName().c_str());
1703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 }
1705 }
1706}
1707
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001708void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1709 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1710 // If the policy decides to close the app, we will get a channel removal event via
1711 // unregisterInputChannel, and will clean up the connection that way. We are already not
1712 // sending new pointers to the connection when it blocked, but focused events will continue to
1713 // pile up.
1714 ALOGW("Canceling events for %s because it is unresponsive",
1715 connection->inputChannel->getName().c_str());
1716 if (connection->status == Connection::STATUS_NORMAL) {
1717 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1718 "application not responding");
1719 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 }
1721}
1722
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001723void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001724 if (DEBUG_FOCUS) {
1725 ALOGD("Resetting ANR timeouts.");
1726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727
1728 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001729 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001730 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731}
1732
Tiger Huang721e26f2018-07-24 22:26:19 +08001733/**
1734 * Get the display id that the given event should go to. If this event specifies a valid display id,
1735 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1736 * Focused display is the display that the user most recently interacted with.
1737 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001738int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001739 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001740 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001741 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001742 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1743 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001744 break;
1745 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001746 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001747 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1748 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 break;
1750 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001751 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001752 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001753 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001754 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001755 case EventEntry::Type::SENSOR:
1756 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001757 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001758 return ADISPLAY_ID_NONE;
1759 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001760 }
1761 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1762}
1763
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001764bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1765 const char* focusedWindowName) {
1766 if (mAnrTracker.empty()) {
1767 // already processed all events that we waited for
1768 mKeyIsWaitingForEventsTimeout = std::nullopt;
1769 return false;
1770 }
1771
1772 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1773 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001774 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001775 mKeyIsWaitingForEventsTimeout = currentTime +
1776 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1777 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001778 return true;
1779 }
1780
1781 // We still have pending events, and already started the timer
1782 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1783 return true; // Still waiting
1784 }
1785
1786 // Waited too long, and some connection still hasn't processed all motions
1787 // Just send the key to the focused window
1788 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1789 focusedWindowName);
1790 mKeyIsWaitingForEventsTimeout = std::nullopt;
1791 return false;
1792}
1793
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001794InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1795 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1796 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001797 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798
Tiger Huang721e26f2018-07-24 22:26:19 +08001799 int32_t displayId = getTargetDisplayId(entry);
chaviw3277faf2021-05-19 16:45:23 -05001800 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001801 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001802 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1803
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 // If there is no currently focused window and no focused application
1805 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001806 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1807 ALOGI("Dropping %s event because there is no focused window or focused application in "
1808 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001809 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001810 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 }
1812
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001813 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1814 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1815 // start interacting with another application via touch (app switch). This code can be removed
1816 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1817 // an app is expected to have a focused window.
1818 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1819 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1820 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001821 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1822 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1823 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001824 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001825 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001826 ALOGW("Waiting because no window has focus but %s may eventually add a "
1827 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001828 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1832 // Already raised ANR. Drop the event
1833 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001834 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 } else {
1837 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001838 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839 }
1840 }
1841
1842 // we have a valid, non-null focused window
1843 resetNoFocusedWindowTimeoutLocked();
1844
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001846 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 }
1849
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001850 if (focusedWindowHandle->getInfo()->paused) {
1851 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001853 }
1854
1855 // If the event is a key event, then we must wait for all previous events to
1856 // complete before delivering it because previous events may have the
1857 // side-effect of transferring focus to a different window and we want to
1858 // ensure that the following keys are sent to the new window.
1859 //
1860 // Suppose the user touches a button in a window then immediately presses "A".
1861 // If the button causes a pop-up window to appear then we want to ensure that
1862 // the "A" key is delivered to the new pop-up window. This is because users
1863 // often anticipate pending UI changes when typing on a keyboard.
1864 // To obtain this behavior, we must serialize key events with respect to all
1865 // prior input events.
1866 if (entry.type == EventEntry::Type::KEY) {
1867 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1868 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001869 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
1872
1873 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001874 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001875 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1876 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877
1878 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880}
1881
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882/**
1883 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1884 * that are currently unresponsive.
1885 */
1886std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1887 const std::vector<TouchedMonitor>& monitors) const {
1888 std::vector<TouchedMonitor> responsiveMonitors;
1889 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1890 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1891 sp<Connection> connection = getConnectionLocked(
1892 monitor.monitor.inputChannel->getConnectionToken());
1893 if (connection == nullptr) {
1894 ALOGE("Could not find connection for monitor %s",
1895 monitor.monitor.inputChannel->getName().c_str());
1896 return false;
1897 }
1898 if (!connection->responsive) {
1899 ALOGW("Unresponsive monitor %s will not get the new gesture",
1900 connection->inputChannel->getName().c_str());
1901 return false;
1902 }
1903 return true;
1904 });
1905 return responsiveMonitors;
1906}
1907
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1909 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1910 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001911 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 enum InjectionPermission {
1913 INJECTION_PERMISSION_UNKNOWN,
1914 INJECTION_PERMISSION_GRANTED,
1915 INJECTION_PERMISSION_DENIED
1916 };
1917
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 // For security reasons, we defer updating the touch state until we are sure that
1919 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001920 int32_t displayId = entry.displayId;
1921 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1923
1924 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001925 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw3277faf2021-05-19 16:45:23 -05001927 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1928 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001930 // Copy current touch state into tempTouchState.
1931 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1932 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001933 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001934 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001935 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1936 mTouchStatesByDisplay.find(displayId);
1937 if (oldStateIt != mTouchStatesByDisplay.end()) {
1938 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001940 }
1941
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001942 bool isSplit = tempTouchState.split;
1943 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1944 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1945 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001946 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1947 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1948 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1949 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1950 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001951 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 bool wrongDevice = false;
1953 if (newGesture) {
1954 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001955 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001956 ALOGI("Dropping event because a pointer for a different device is already down "
1957 "in display %" PRId32,
1958 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001959 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001960 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 switchedDevice = false;
1962 wrongDevice = true;
1963 goto Failed;
1964 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001965 tempTouchState.reset();
1966 tempTouchState.down = down;
1967 tempTouchState.deviceId = entry.deviceId;
1968 tempTouchState.source = entry.source;
1969 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001971 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001972 ALOGI("Dropping move event because a pointer for a different device is already active "
1973 "in display %" PRId32,
1974 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001975 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001976 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001977 switchedDevice = false;
1978 wrongDevice = true;
1979 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981
1982 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1983 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1984
Garfield Tan00f511d2019-06-12 16:55:40 -07001985 int32_t x;
1986 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001988 // Always dispatch mouse events to cursor position.
1989 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001990 x = int32_t(entry.xCursorPosition);
1991 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001992 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001993 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1994 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001995 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001996 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001997 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001998 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1999 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002000
2001 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002002 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002003 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002006 if (newTouchedWindowHandle != nullptr &&
2007 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002008 // New window supports splitting, but we should never split mouse events.
2009 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 } else if (isSplit) {
2011 // New window does not support splitting but we have already split events.
2012 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002013 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 }
2015
2016 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002017 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002019 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002020 }
2021
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002022 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2023 ALOGI("Not sending touch event to %s because it is paused",
2024 newTouchedWindowHandle->getName().c_str());
2025 newTouchedWindowHandle = nullptr;
2026 }
2027
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002028 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002029 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002030 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2031 if (!isResponsive) {
2032 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002033 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2034 newTouchedWindowHandle = nullptr;
2035 }
2036 }
2037
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002038 // Drop events that can't be trusted due to occlusion
2039 if (newTouchedWindowHandle != nullptr &&
2040 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2041 TouchOcclusionInfo occlusionInfo =
2042 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002043 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002044 if (DEBUG_TOUCH_OCCLUSION) {
2045 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2046 for (const auto& log : occlusionInfo.debugInfo) {
2047 ALOGD("%s", log.c_str());
2048 }
2049 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002050 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2051 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2052 ALOGW("Dropping untrusted touch event due to %s/%d",
2053 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2054 newTouchedWindowHandle = nullptr;
2055 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002056 }
2057 }
2058
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002059 // Also don't send the new touch event to unresponsive gesture monitors
2060 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2061
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2063 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 "(%d, %d) in display %" PRId32 ".",
2065 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002066 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002067 goto Failed;
2068 }
2069
2070 if (newTouchedWindowHandle != nullptr) {
2071 // Set target flags.
2072 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2073 if (isSplit) {
2074 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002076 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2077 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2078 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2079 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2080 }
2081
2082 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002083 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2084 newHoverWindowHandle = nullptr;
2085 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002086 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002087 }
2088
2089 // Update the temporary touch state.
2090 BitSet32 pointerIds;
2091 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002092 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002093 pointerIds.markBit(pointerId);
2094 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
2097
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002098 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 } else {
2100 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2101
2102 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002103 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002104 if (DEBUG_FOCUS) {
2105 ALOGD("Dropping event because the pointer is not down or we previously "
2106 "dropped the pointer down event in display %" PRId32,
2107 displayId);
2108 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002109 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 goto Failed;
2111 }
2112
arthurhung6d4bed92021-03-17 11:59:33 +08002113 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002114
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002116 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002117 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002118 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2119 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120
chaviw3277faf2021-05-19 16:45:23 -05002121 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002123 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002124 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2125 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002126 if (DEBUG_FOCUS) {
2127 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2128 oldTouchedWindowHandle->getName().c_str(),
2129 newTouchedWindowHandle->getName().c_str(), displayId);
2130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002132 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2133 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2134 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135
2136 // Make a slippery entrance into the new window.
2137 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2138 isSplit = true;
2139 }
2140
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141 int32_t targetFlags =
2142 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 if (isSplit) {
2144 targetFlags |= InputTarget::FLAG_SPLIT;
2145 }
2146 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2147 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002148 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2149 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
2151
2152 BitSet32 pointerIds;
2153 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002154 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
2158 }
2159 }
2160
2161 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002162 // Let the previous window know that the hover sequence is over, unless we already did it
2163 // when dispatching it as is to newTouchedWindowHandle.
2164 if (mLastHoverWindowHandle != nullptr &&
2165 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2166 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#if DEBUG_HOVER
2168 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002169 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002171 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2172 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
2174
Garfield Tandf26e862020-07-01 20:18:19 -07002175 // Let the new window know that the hover sequence is starting, unless we already did it
2176 // when dispatching it as is to newTouchedWindowHandle.
2177 if (newHoverWindowHandle != nullptr &&
2178 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2179 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180#if DEBUG_HOVER
2181 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002182 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002184 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2185 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2186 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 }
2188 }
2189
2190 // Check permission to inject into all touched foreground windows and ensure there
2191 // is at least one touched foreground window.
2192 {
2193 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2196 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002197 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002198 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 injectionPermission = INJECTION_PERMISSION_DENIED;
2200 goto Failed;
2201 }
2202 }
2203 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002205 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002206 ALOGI("Dropping event because there is no touched foreground window in display "
2207 "%" PRId32 " or gesture monitor to receive it.",
2208 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002209 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 goto Failed;
2211 }
2212
2213 // Permission granted to injection into all touched foreground windows.
2214 injectionPermission = INJECTION_PERMISSION_GRANTED;
2215 }
2216
2217 // Check whether windows listening for outside touches are owned by the same UID. If it is
2218 // set the policy flag that we will not reveal coordinate information to this window.
2219 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002220 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002221 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (foregroundWindowHandle) {
2223 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002224 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002225 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw3277faf2021-05-19 16:45:23 -05002226 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2227 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2228 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 InputTarget::FLAG_ZERO_COORDS,
2230 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 }
2233 }
2234 }
2235 }
2236
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 // If this is the first pointer going down and the touched window has a wallpaper
2238 // then also add the touched wallpaper windows so they are locked in for the duration
2239 // of the touch gesture.
2240 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2241 // engine only supports touch events. We would need to add a mechanism similar
2242 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2243 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002244 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002245 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002246 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw3277faf2021-05-19 16:45:23 -05002247 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002248 getWindowHandlesLocked(displayId);
chaviw3277faf2021-05-19 16:45:23 -05002249 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2250 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002251 if (info->displayId == displayId &&
chaviw3277faf2021-05-19 16:45:23 -05002252 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002253 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 .addOrUpdateWindow(windowHandle,
2255 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2256 InputTarget::
2257 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2258 InputTarget::FLAG_DISPATCH_AS_IS,
2259 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 }
2261 }
2262 }
2263 }
2264
2265 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002266 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002268 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
2272
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002273 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002274 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002276 }
2277
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 // Drop the outside or hover touch windows since we will not care about them
2279 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281
2282Failed:
2283 // Check injection permission once and for all.
2284 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002285 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 injectionPermission = INJECTION_PERMISSION_GRANTED;
2287 } else {
2288 injectionPermission = INJECTION_PERMISSION_DENIED;
2289 }
2290 }
2291
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002292 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2293 return injectionResult;
2294 }
2295
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002297 if (!wrongDevice) {
2298 if (switchedDevice) {
2299 if (DEBUG_FOCUS) {
2300 ALOGD("Conflicting pointer actions: Switched to a different device.");
2301 }
2302 *outConflictingPointerActions = true;
2303 }
2304
2305 if (isHoverAction) {
2306 // Started hovering, therefore no longer down.
2307 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002308 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002309 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2310 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 *outConflictingPointerActions = true;
2313 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002314 tempTouchState.reset();
2315 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2316 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2317 tempTouchState.deviceId = entry.deviceId;
2318 tempTouchState.source = entry.source;
2319 tempTouchState.displayId = displayId;
2320 }
2321 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2322 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2323 // All pointers up or canceled.
2324 tempTouchState.reset();
2325 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2326 // First pointer went down.
2327 if (oldState && oldState->down) {
2328 if (DEBUG_FOCUS) {
2329 ALOGD("Conflicting pointer actions: Down received while already down.");
2330 }
2331 *outConflictingPointerActions = true;
2332 }
2333 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2334 // One pointer went up.
2335 if (isSplit) {
2336 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2337 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002339 for (size_t i = 0; i < tempTouchState.windows.size();) {
2340 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2341 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2342 touchedWindow.pointerIds.clearBit(pointerId);
2343 if (touchedWindow.pointerIds.isEmpty()) {
2344 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2345 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002348 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002350 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002351 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002352
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002353 // Save changes unless the action was scroll in which case the temporary touch
2354 // state was only valid for this one action.
2355 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2356 if (tempTouchState.displayId >= 0) {
2357 mTouchStatesByDisplay[displayId] = tempTouchState;
2358 } else {
2359 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002363 // Update hover state.
2364 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
2366
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 return injectionResult;
2368}
2369
arthurhung6d4bed92021-03-17 11:59:33 +08002370void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw3277faf2021-05-19 16:45:23 -05002371 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002372 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2373 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2374 true /*ignoreDragWindow*/);
2375 if (dropWindow) {
2376 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2377 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002378 } else {
2379 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002380 }
2381 mDragState.reset();
2382}
2383
2384void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2385 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002386 return;
2387 }
2388
arthurhung6d4bed92021-03-17 11:59:33 +08002389 if (!mDragState->isStartDrag) {
2390 mDragState->isStartDrag = true;
2391 mDragState->isStylusButtonDownAtStart =
2392 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2393 }
2394
arthurhungb89ccb02020-12-30 16:19:01 +08002395 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2396 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2397 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2398 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002399 // Handle the special case : stylus button no longer pressed.
2400 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2401 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2402 finishDragAndDrop(entry.displayId, x, y);
2403 return;
2404 }
2405
chaviw3277faf2021-05-19 16:45:23 -05002406 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002407 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002408 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2409 true /*ignoreDragWindow*/);
2410 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002411 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2412 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2413 if (mDragState->dragHoverWindowHandle != nullptr) {
2414 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2415 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002416 }
arthurhung6d4bed92021-03-17 11:59:33 +08002417 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002418 }
2419 // enqueue drag location if needed.
2420 if (hoverWindowHandle != nullptr) {
2421 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2422 }
arthurhung6d4bed92021-03-17 11:59:33 +08002423 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2424 finishDragAndDrop(entry.displayId, x, y);
2425 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002426 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002427 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002428 }
2429}
2430
chaviw3277faf2021-05-19 16:45:23 -05002431void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002432 int32_t targetFlags, BitSet32 pointerIds,
2433 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002434 std::vector<InputTarget>::iterator it =
2435 std::find_if(inputTargets.begin(), inputTargets.end(),
2436 [&windowHandle](const InputTarget& inputTarget) {
2437 return inputTarget.inputChannel->getConnectionToken() ==
2438 windowHandle->getToken();
2439 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002440
chaviw3277faf2021-05-19 16:45:23 -05002441 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002442
2443 if (it == inputTargets.end()) {
2444 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002445 std::shared_ptr<InputChannel> inputChannel =
2446 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002447 if (inputChannel == nullptr) {
2448 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2449 return;
2450 }
2451 inputTarget.inputChannel = inputChannel;
2452 inputTarget.flags = targetFlags;
2453 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002454 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002455 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002456 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002457 inputTargets.push_back(inputTarget);
2458 it = inputTargets.end() - 1;
2459 }
2460
2461 ALOG_ASSERT(it->flags == targetFlags);
2462 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2463
chaviw1ff3d1e2020-07-01 15:53:47 -07002464 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465}
2466
Michael Wright3dd60e22019-03-27 22:06:44 +00002467void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002468 int32_t displayId, float xOffset,
2469 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002470 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2471 mGlobalMonitorsByDisplay.find(displayId);
2472
2473 if (it != mGlobalMonitorsByDisplay.end()) {
2474 const std::vector<Monitor>& monitors = it->second;
2475 for (const Monitor& monitor : monitors) {
2476 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
2479}
2480
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002481void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2482 float yOffset,
2483 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002484 InputTarget target;
2485 target.inputChannel = monitor.inputChannel;
2486 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002487 ui::Transform t;
2488 t.set(xOffset, yOffset);
2489 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002490 inputTargets.push_back(target);
2491}
2492
chaviw3277faf2021-05-19 16:45:23 -05002493bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002494 const InjectionState* injectionState) {
2495 if (injectionState &&
2496 (windowHandle == nullptr ||
2497 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2498 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002499 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002501 "owned by uid %d",
2502 injectionState->injectorPid, injectionState->injectorUid,
2503 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 } else {
2505 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 }
2508 return false;
2509 }
2510 return true;
2511}
2512
Robert Carrc9bf1d32020-04-13 17:21:08 -07002513/**
2514 * Indicate whether one window handle should be considered as obscuring
2515 * another window handle. We only check a few preconditions. Actually
2516 * checking the bounds is left to the caller.
2517 */
chaviw3277faf2021-05-19 16:45:23 -05002518static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2519 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002520 // Compare by token so cloned layers aren't counted
2521 if (haveSameToken(windowHandle, otherHandle)) {
2522 return false;
2523 }
2524 auto info = windowHandle->getInfo();
2525 auto otherInfo = otherHandle->getInfo();
2526 if (!otherInfo->visible) {
2527 return false;
chaviw3277faf2021-05-19 16:45:23 -05002528 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002529 // Those act as if they were invisible, so we don't need to flag them.
2530 // We do want to potentially flag touchable windows even if they have 0
2531 // opacity, since they can consume touches and alter the effects of the
2532 // user interaction (eg. apps that rely on
2533 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2534 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2535 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002536 } else if (info->ownerUid == otherInfo->ownerUid) {
2537 // If ownerUid is the same we don't generate occlusion events as there
2538 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002539 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002540 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002541 return false;
2542 } else if (otherInfo->displayId != info->displayId) {
2543 return false;
2544 }
2545 return true;
2546}
2547
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002548/**
2549 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2550 * untrusted, one should check:
2551 *
2552 * 1. If result.hasBlockingOcclusion is true.
2553 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2554 * BLOCK_UNTRUSTED.
2555 *
2556 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2557 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2558 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2559 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2560 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2561 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2562 *
2563 * If neither of those is true, then it means the touch can be allowed.
2564 */
2565InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw3277faf2021-05-19 16:45:23 -05002566 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2567 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002568 int32_t displayId = windowInfo->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002569 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002570 TouchOcclusionInfo info;
2571 info.hasBlockingOcclusion = false;
2572 info.obscuringOpacity = 0;
2573 info.obscuringUid = -1;
2574 std::map<int32_t, float> opacityByUid;
chaviw3277faf2021-05-19 16:45:23 -05002575 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002576 if (windowHandle == otherHandle) {
2577 break; // All future windows are below us. Exit early.
2578 }
chaviw3277faf2021-05-19 16:45:23 -05002579 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002580 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2581 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002582 if (DEBUG_TOUCH_OCCLUSION) {
2583 info.debugInfo.push_back(
2584 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2585 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002586 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2587 // we perform the checks below to see if the touch can be propagated or not based on the
2588 // window's touch occlusion mode
2589 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2590 info.hasBlockingOcclusion = true;
2591 info.obscuringUid = otherInfo->ownerUid;
2592 info.obscuringPackage = otherInfo->packageName;
2593 break;
2594 }
2595 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2596 uint32_t uid = otherInfo->ownerUid;
2597 float opacity =
2598 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2599 // Given windows A and B:
2600 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2601 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2602 opacityByUid[uid] = opacity;
2603 if (opacity > info.obscuringOpacity) {
2604 info.obscuringOpacity = opacity;
2605 info.obscuringUid = uid;
2606 info.obscuringPackage = otherInfo->packageName;
2607 }
2608 }
2609 }
2610 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002611 if (DEBUG_TOUCH_OCCLUSION) {
2612 info.debugInfo.push_back(
2613 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2614 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002615 return info;
2616}
2617
chaviw3277faf2021-05-19 16:45:23 -05002618std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002619 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002620 return StringPrintf(INDENT2
2621 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2622 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2623 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2624 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002625 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002626 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002627 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002628 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2629 info->frameTop, info->frameRight, info->frameBottom,
2630 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002631 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2632 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2633 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002634}
2635
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002636bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2637 if (occlusionInfo.hasBlockingOcclusion) {
2638 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2639 occlusionInfo.obscuringUid);
2640 return false;
2641 }
2642 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2643 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2644 "%.2f, maximum allowed = %.2f)",
2645 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2646 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2647 return false;
2648 }
2649 return true;
2650}
2651
chaviw3277faf2021-05-19 16:45:23 -05002652bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002653 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002655 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2656 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002657 if (windowHandle == otherHandle) {
2658 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 }
chaviw3277faf2021-05-19 16:45:23 -05002660 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002661 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002662 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 return true;
2664 }
2665 }
2666 return false;
2667}
2668
chaviw3277faf2021-05-19 16:45:23 -05002669bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002670 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002671 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2672 const WindowInfo* windowInfo = windowHandle->getInfo();
2673 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002674 if (windowHandle == otherHandle) {
2675 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002676 }
chaviw3277faf2021-05-19 16:45:23 -05002677 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002678 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002679 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002680 return true;
2681 }
2682 }
2683 return false;
2684}
2685
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002686std::string InputDispatcher::getApplicationWindowLabel(
chaviw3277faf2021-05-19 16:45:23 -05002687 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002688 if (applicationHandle != nullptr) {
2689 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002690 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 } else {
2692 return applicationHandle->getName();
2693 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002694 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002695 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002697 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 }
2699}
2700
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002701void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002702 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002703 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2704 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002705 // Focus or pointer capture changed events are passed to apps, but do not represent user
2706 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002707 return;
2708 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002709 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw3277faf2021-05-19 16:45:23 -05002710 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002711 if (focusedWindowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05002712 const WindowInfo* info = focusedWindowHandle->getInfo();
2713 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002715 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716#endif
2717 return;
2718 }
2719 }
2720
2721 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002722 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002723 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002724 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2725 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 return;
2727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002729 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 eventType = USER_ACTIVITY_EVENT_TOUCH;
2731 }
2732 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002734 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002735 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2736 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 return;
2738 }
2739 eventType = USER_ACTIVITY_EVENT_BUTTON;
2740 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002742 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002743 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002744 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002745 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002746 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2747 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002748 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002749 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002750 break;
2751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
2753
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002754 std::unique_ptr<CommandEntry> commandEntry =
2755 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002756 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002758 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002759 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760}
2761
2762void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002764 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002765 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002766 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002767 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002768 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002769 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002770 ATRACE_NAME(message.c_str());
2771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772#if DEBUG_DISPATCH_CYCLE
2773 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002774 "globalScaleFactor=%f, pointerIds=0x%x %s",
2775 connection->getInputChannelName().c_str(), inputTarget.flags,
2776 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2777 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778#endif
2779
2780 // Skip this event if the connection status is not normal.
2781 // We don't want to enqueue additional outbound events if the connection is broken.
2782 if (connection->status != Connection::STATUS_NORMAL) {
2783#if DEBUG_DISPATCH_CYCLE
2784 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786#endif
2787 return;
2788 }
2789
2790 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002791 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2792 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2793 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002794 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002796 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002797 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002798 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002799 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 if (!splitMotionEntry) {
2801 return; // split event was dropped
2802 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002803 if (DEBUG_FOCUS) {
2804 ALOGD("channel '%s' ~ Split motion event.",
2805 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002806 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002807 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002808 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2809 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 return;
2811 }
2812 }
2813
2814 // Not splitting. Enqueue dispatch entries for the event as is.
2815 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2816}
2817
2818void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002819 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002820 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002821 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002822 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002824 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002825 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002826 ATRACE_NAME(message.c_str());
2827 }
2828
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002829 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830
2831 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002832 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002834 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002836 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002840 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844
2845 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002846 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 startDispatchCycleLocked(currentTime, connection);
2848 }
2849}
2850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002852 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002853 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002855 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002856 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2857 connection->getInputChannelName().c_str(),
2858 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002859 ATRACE_NAME(message.c_str());
2860 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002861 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 if (!(inputTargetFlags & dispatchMode)) {
2863 return;
2864 }
2865 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2866
2867 // This is a new event.
2868 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002869 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002872 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2873 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002874 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002876 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002877 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002878 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002879 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002880 dispatchEntry->resolvedAction = keyEntry.action;
2881 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002883 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2884 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2887 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 return; // skip the inconsistent event
2890 }
2891 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002894 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002895 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002896 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2897 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2898 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2899 static_cast<int32_t>(IdGenerator::Source::OTHER);
2900 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2902 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2903 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2904 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2905 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2906 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2907 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2908 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2909 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2910 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2911 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002913 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 }
2915 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002916 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2917 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2920 "event",
2921 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002923 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2924 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002928 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2930 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2931 }
2932 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2933 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2937 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2940 "event",
2941 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 return; // skip the inconsistent event
2944 }
2945
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002946 dispatchEntry->resolvedEventId =
2947 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2948 ? mIdGenerator.nextId()
2949 : motionEntry.id;
2950 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2951 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2952 ") to MotionEvent(id=0x%" PRIx32 ").",
2953 motionEntry.id, dispatchEntry->resolvedEventId);
2954 ATRACE_NAME(message.c_str());
2955 }
2956
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002957 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2958 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2959 // Skip reporting pointer down outside focus to the policy.
2960 break;
2961 }
2962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002963 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002964 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965
2966 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002968 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002969 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2970 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002971 break;
2972 }
Chris Yef59a2f42020-10-16 12:55:26 -07002973 case EventEntry::Type::SENSOR: {
2974 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2975 break;
2976 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002977 case EventEntry::Type::CONFIGURATION_CHANGED:
2978 case EventEntry::Type::DEVICE_RESET: {
2979 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002980 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002981 break;
2982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983 }
2984
2985 // Remember that we are waiting for this dispatch to complete.
2986 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002987 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
2989
2990 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002991 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002992 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002993}
2994
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002995/**
2996 * This function is purely for debugging. It helps us understand where the user interaction
2997 * was taking place. For example, if user is touching launcher, we will see a log that user
2998 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2999 * We will see both launcher and wallpaper in that list.
3000 * Once the interaction with a particular set of connections starts, no new logs will be printed
3001 * until the set of interacted connections changes.
3002 *
3003 * The following items are skipped, to reduce the logspam:
3004 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3005 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3006 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3007 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3008 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003009 */
3010void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3011 const std::vector<InputTarget>& targets) {
3012 // Skip ACTION_UP events, and all events other than keys and motions
3013 if (entry.type == EventEntry::Type::KEY) {
3014 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3015 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3016 return;
3017 }
3018 } else if (entry.type == EventEntry::Type::MOTION) {
3019 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3020 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3021 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3022 return;
3023 }
3024 } else {
3025 return; // Not a key or a motion
3026 }
3027
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003028 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003029 std::vector<sp<Connection>> newConnections;
3030 for (const InputTarget& target : targets) {
3031 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3032 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3033 continue; // Skip windows that receive ACTION_OUTSIDE
3034 }
3035
3036 sp<IBinder> token = target.inputChannel->getConnectionToken();
3037 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003038 if (connection == nullptr) {
3039 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003040 }
3041 newConnectionTokens.insert(std::move(token));
3042 newConnections.emplace_back(connection);
3043 }
3044 if (newConnectionTokens == mInteractionConnectionTokens) {
3045 return; // no change
3046 }
3047 mInteractionConnectionTokens = newConnectionTokens;
3048
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003049 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003050 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003051 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003052 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003053 std::string message = "Interaction with: " + targetList;
3054 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003055 message += "<none>";
3056 }
3057 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3058}
3059
chaviwfd6d3512019-03-25 13:23:49 -07003060void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003061 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003062 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003063 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3064 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003065 return;
3066 }
3067
Vishnu Nairc519ff72021-01-21 08:23:08 -08003068 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003069 if (focusedToken == token) {
3070 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003071 return;
3072 }
3073
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003074 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3075 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003076 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003077 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078}
3079
3080void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003082 if (ATRACE_ENABLED()) {
3083 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003085 ATRACE_NAME(message.c_str());
3086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#endif
3090
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003091 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3092 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003094 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003095 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003096 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
3098 // Publish the event.
3099 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003100 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3101 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003102 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003103 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3104 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003107 status = connection->inputPublisher
3108 .publishKeyEvent(dispatchEntry->seq,
3109 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3110 keyEntry.source, keyEntry.displayId,
3111 std::move(hmac), dispatchEntry->resolvedAction,
3112 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3113 keyEntry.scanCode, keyEntry.metaState,
3114 keyEntry.repeatCount, keyEntry.downTime,
3115 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003119 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003120 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003123 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124
chaviw82357092020-01-28 13:13:06 -08003125 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3128 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003129 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003130 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3131 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003132 // Don't apply window scale here since we don't want scale to affect raw
3133 // coordinates. The scale will be sent back to the client and applied
3134 // later when requesting relative coordinates.
3135 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3136 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 }
3138 usingCoords = scaledCoords;
3139 }
3140 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 // We don't want the dispatch target to know.
3142 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003143 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 scaledCoords[i].clear();
3145 }
3146 usingCoords = scaledCoords;
3147 }
3148 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003150 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003151
3152 // Publish the motion event.
3153 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003154 .publishMotionEvent(dispatchEntry->seq,
3155 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003156 motionEntry.deviceId, motionEntry.source,
3157 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003158 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003159 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 motionEntry.edgeFlags, motionEntry.metaState,
3162 motionEntry.buttonState,
3163 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003164 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 motionEntry.xPrecision, motionEntry.yPrecision,
3166 motionEntry.xCursorPosition,
3167 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003168 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003169 dispatchEntry->displaySize.x,
3170 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003171 motionEntry.downTime, motionEntry.eventTime,
3172 motionEntry.pointerCount,
3173 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003174 break;
3175 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003176
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003177 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003178 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003179 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 focusEntry.id,
3181 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003182 mInTouchMode);
3183 break;
3184 }
3185
Prabir Pradhan99987712020-11-10 18:43:05 -08003186 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3187 const auto& captureEntry =
3188 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3189 status = connection->inputPublisher
3190 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3191 captureEntry.pointerCaptureEnabled);
3192 break;
3193 }
3194
arthurhungb89ccb02020-12-30 16:19:01 +08003195 case EventEntry::Type::DRAG: {
3196 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3197 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3198 dragEntry.id, dragEntry.x,
3199 dragEntry.y,
3200 dragEntry.isExiting);
3201 break;
3202 }
3203
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003204 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003205 case EventEntry::Type::DEVICE_RESET:
3206 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003207 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003208 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 }
3212
3213 // Check the result.
3214 if (status) {
3215 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003216 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 "This is unexpected because the wait queue is empty, so the pipe "
3219 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003220 "event to it, status=%s(%d)",
3221 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3222 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3224 } else {
3225 // Pipe is full and we are waiting for the app to finish process some events
3226 // before sending more events to it.
3227#if DEBUG_DISPATCH_CYCLE
3228 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 "waiting for the application to catch up",
3230 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 }
3233 } else {
3234 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003235 "status=%s(%d)",
3236 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3237 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3239 }
3240 return;
3241 }
3242
3243 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003244 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3245 connection->outboundQueue.end(),
3246 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003247 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003248 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003249 if (connection->responsive) {
3250 mAnrTracker.insert(dispatchEntry->timeoutTime,
3251 connection->inputChannel->getConnectionToken());
3252 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003253 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 }
3255}
3256
chaviw09c8d2d2020-08-24 15:48:26 -07003257std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3258 size_t size;
3259 switch (event.type) {
3260 case VerifiedInputEvent::Type::KEY: {
3261 size = sizeof(VerifiedKeyEvent);
3262 break;
3263 }
3264 case VerifiedInputEvent::Type::MOTION: {
3265 size = sizeof(VerifiedMotionEvent);
3266 break;
3267 }
3268 }
3269 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3270 return mHmacKeyManager.sign(start, size);
3271}
3272
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003273const std::array<uint8_t, 32> InputDispatcher::getSignature(
3274 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3275 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3276 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3277 // Only sign events up and down events as the purely move events
3278 // are tied to their up/down counterparts so signing would be redundant.
3279 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3280 verifiedEvent.actionMasked = actionMasked;
3281 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003282 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003283 }
3284 return INVALID_HMAC;
3285}
3286
3287const std::array<uint8_t, 32> InputDispatcher::getSignature(
3288 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3289 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3290 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3291 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003292 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003293}
3294
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003297 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298#if DEBUG_DISPATCH_CYCLE
3299 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301#endif
3302
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303 if (connection->status == Connection::STATUS_BROKEN ||
3304 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 return;
3306 }
3307
3308 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003309 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310}
3311
3312void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 const sp<Connection>& connection,
3314 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315#if DEBUG_DISPATCH_CYCLE
3316 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318#endif
3319
3320 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003321 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003322 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003323 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003324 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325
3326 // The connection appears to be unrecoverably broken.
3327 // Ignore already broken or zombie connections.
3328 if (connection->status == Connection::STATUS_NORMAL) {
3329 connection->status = Connection::STATUS_BROKEN;
3330
3331 if (notify) {
3332 // Notify other system components.
3333 onDispatchCycleBrokenLocked(currentTime, connection);
3334 }
3335 }
3336}
3337
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003338void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3339 while (!queue.empty()) {
3340 DispatchEntry* dispatchEntry = queue.front();
3341 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003342 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
3344}
3345
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003346void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003348 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 }
3350 delete dispatchEntry;
3351}
3352
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003353int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3354 std::scoped_lock _l(mLock);
3355 sp<Connection> connection = getConnectionLocked(connectionToken);
3356 if (connection == nullptr) {
3357 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3358 connectionToken.get(), events);
3359 return 0; // remove the callback
3360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003362 bool notify;
3363 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3364 if (!(events & ALOOPER_EVENT_INPUT)) {
3365 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3366 "events=0x%x",
3367 connection->getInputChannelName().c_str(), events);
3368 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 }
3370
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003371 nsecs_t currentTime = now();
3372 bool gotOne = false;
3373 status_t status = OK;
3374 for (;;) {
3375 Result<InputPublisher::ConsumerResponse> result =
3376 connection->inputPublisher.receiveConsumerResponse();
3377 if (!result.ok()) {
3378 status = result.error().code();
3379 break;
3380 }
3381
3382 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3383 const InputPublisher::Finished& finish =
3384 std::get<InputPublisher::Finished>(*result);
3385 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3386 finish.consumeTime);
3387 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003388 if (shouldReportMetricsForConnection(*connection)) {
3389 const InputPublisher::Timeline& timeline =
3390 std::get<InputPublisher::Timeline>(*result);
3391 mLatencyTracker
3392 .trackGraphicsLatency(timeline.inputEventId,
3393 connection->inputChannel->getConnectionToken(),
3394 std::move(timeline.graphicsTimeline));
3395 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003396 }
3397 gotOne = true;
3398 }
3399 if (gotOne) {
3400 runCommandsLockedInterruptible();
3401 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 return 1;
3403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 }
3405
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003406 notify = status != DEAD_OBJECT || !connection->monitor;
3407 if (notify) {
3408 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3409 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3410 status);
3411 }
3412 } else {
3413 // Monitor channels are never explicitly unregistered.
3414 // We do it automatically when the remote endpoint is closed so don't warn about them.
3415 const bool stillHaveWindowHandle =
3416 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3417 notify = !connection->monitor && stillHaveWindowHandle;
3418 if (notify) {
3419 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3420 connection->getInputChannelName().c_str(), events);
3421 }
3422 }
3423
3424 // Remove the channel.
3425 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3426 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427}
3428
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003429void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003431 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003432 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 }
3434}
3435
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003436void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003437 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003438 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3439 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3440}
3441
3442void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3443 const CancelationOptions& options,
3444 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3445 for (const auto& it : monitorsByDisplay) {
3446 const std::vector<Monitor>& monitors = it.second;
3447 for (const Monitor& monitor : monitors) {
3448 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003449 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003450 }
3451}
3452
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003454 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003455 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003456 if (connection == nullptr) {
3457 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003459
3460 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461}
3462
3463void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3464 const sp<Connection>& connection, const CancelationOptions& options) {
3465 if (connection->status == Connection::STATUS_BROKEN) {
3466 return;
3467 }
3468
3469 nsecs_t currentTime = now();
3470
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003471 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003472 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003474 if (cancelationEvents.empty()) {
3475 return;
3476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003478 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3479 "with reality: %s, mode=%d.",
3480 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3481 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003483
3484 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003485 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003486 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3487 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003488 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003489 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003490 target.globalScaleFactor = windowInfo->globalScaleFactor;
3491 }
3492 target.inputChannel = connection->inputChannel;
3493 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3494
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003495 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003496 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003497 switch (cancelationEventEntry->type) {
3498 case EventEntry::Type::KEY: {
3499 logOutboundKeyDetails("cancel - ",
3500 static_cast<const KeyEntry&>(*cancelationEventEntry));
3501 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003503 case EventEntry::Type::MOTION: {
3504 logOutboundMotionDetails("cancel - ",
3505 static_cast<const MotionEntry&>(*cancelationEventEntry));
3506 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003508 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003509 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3510 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003511 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003512 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003513 break;
3514 }
3515 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003516 case EventEntry::Type::DEVICE_RESET:
3517 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003518 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003519 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003520 break;
3521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
3523
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003524 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3525 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003527
3528 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529}
3530
Svet Ganov5d3bc372020-01-26 23:11:07 -08003531void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3532 const sp<Connection>& connection) {
3533 if (connection->status == Connection::STATUS_BROKEN) {
3534 return;
3535 }
3536
3537 nsecs_t currentTime = now();
3538
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003539 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003540 connection->inputState.synthesizePointerDownEvents(currentTime);
3541
3542 if (downEvents.empty()) {
3543 return;
3544 }
3545
3546#if DEBUG_OUTBOUND_EVENT_DETAILS
3547 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3548 connection->getInputChannelName().c_str(), downEvents.size());
3549#endif
3550
3551 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003552 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003553 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3554 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003555 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003556 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003557 target.globalScaleFactor = windowInfo->globalScaleFactor;
3558 }
3559 target.inputChannel = connection->inputChannel;
3560 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3561
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003562 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003563 switch (downEventEntry->type) {
3564 case EventEntry::Type::MOTION: {
3565 logOutboundMotionDetails("down - ",
3566 static_cast<const MotionEntry&>(*downEventEntry));
3567 break;
3568 }
3569
3570 case EventEntry::Type::KEY:
3571 case EventEntry::Type::FOCUS:
3572 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003573 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003574 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003575 case EventEntry::Type::SENSOR:
3576 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003577 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003578 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003579 break;
3580 }
3581 }
3582
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003583 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3584 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003585 }
3586
3587 startDispatchCycleLocked(currentTime, connection);
3588}
3589
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003590std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3591 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 ALOG_ASSERT(pointerIds.value != 0);
3593
3594 uint32_t splitPointerIndexMap[MAX_POINTERS];
3595 PointerProperties splitPointerProperties[MAX_POINTERS];
3596 PointerCoords splitPointerCoords[MAX_POINTERS];
3597
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003598 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 uint32_t splitPointerCount = 0;
3600
3601 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003602 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003604 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 uint32_t pointerId = uint32_t(pointerProperties.id);
3606 if (pointerIds.hasBit(pointerId)) {
3607 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3608 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3609 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003610 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 splitPointerCount += 1;
3612 }
3613 }
3614
3615 if (splitPointerCount != pointerIds.count()) {
3616 // This is bad. We are missing some of the pointers that we expected to deliver.
3617 // Most likely this indicates that we received an ACTION_MOVE events that has
3618 // different pointer ids than we expected based on the previous ACTION_DOWN
3619 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3620 // in this way.
3621 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003622 "we expected there to be %d pointers. This probably means we received "
3623 "a broken sequence of pointer ids from the input device.",
3624 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003625 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003628 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003630 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3631 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3633 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003634 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 uint32_t pointerId = uint32_t(pointerProperties.id);
3636 if (pointerIds.hasBit(pointerId)) {
3637 if (pointerIds.count() == 1) {
3638 // The first/last pointer went down/up.
3639 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003640 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003641 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3642 ? AMOTION_EVENT_ACTION_CANCEL
3643 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 } else {
3645 // A secondary pointer went down/up.
3646 uint32_t splitPointerIndex = 0;
3647 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3648 splitPointerIndex += 1;
3649 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003650 action = maskedAction |
3651 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653 } else {
3654 // An unrelated pointer changed.
3655 action = AMOTION_EVENT_ACTION_MOVE;
3656 }
3657 }
3658
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003659 int32_t newId = mIdGenerator.nextId();
3660 if (ATRACE_ENABLED()) {
3661 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3662 ") to MotionEvent(id=0x%" PRIx32 ").",
3663 originalMotionEntry.id, newId);
3664 ATRACE_NAME(message.c_str());
3665 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003666 std::unique_ptr<MotionEntry> splitMotionEntry =
3667 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3668 originalMotionEntry.deviceId, originalMotionEntry.source,
3669 originalMotionEntry.displayId,
3670 originalMotionEntry.policyFlags, action,
3671 originalMotionEntry.actionButton,
3672 originalMotionEntry.flags, originalMotionEntry.metaState,
3673 originalMotionEntry.buttonState,
3674 originalMotionEntry.classification,
3675 originalMotionEntry.edgeFlags,
3676 originalMotionEntry.xPrecision,
3677 originalMotionEntry.yPrecision,
3678 originalMotionEntry.xCursorPosition,
3679 originalMotionEntry.yCursorPosition,
3680 originalMotionEntry.downTime, splitPointerCount,
3681 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003683 if (originalMotionEntry.injectionState) {
3684 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 splitMotionEntry->injectionState->refCount += 1;
3686 }
3687
3688 return splitMotionEntry;
3689}
3690
3691void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3692#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003693 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694#endif
3695
3696 bool needWake;
3697 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003698 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003700 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3701 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3702 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 } // release lock
3704
3705 if (needWake) {
3706 mLooper->wake();
3707 }
3708}
3709
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003710/**
3711 * If one of the meta shortcuts is detected, process them here:
3712 * Meta + Backspace -> generate BACK
3713 * Meta + Enter -> generate HOME
3714 * This will potentially overwrite keyCode and metaState.
3715 */
3716void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003717 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003718 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3719 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3720 if (keyCode == AKEYCODE_DEL) {
3721 newKeyCode = AKEYCODE_BACK;
3722 } else if (keyCode == AKEYCODE_ENTER) {
3723 newKeyCode = AKEYCODE_HOME;
3724 }
3725 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003726 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003727 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003728 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003729 keyCode = newKeyCode;
3730 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3731 }
3732 } else if (action == AKEY_EVENT_ACTION_UP) {
3733 // In order to maintain a consistent stream of up and down events, check to see if the key
3734 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3735 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003736 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003737 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003738 auto replacementIt = mReplacedKeys.find(replacement);
3739 if (replacementIt != mReplacedKeys.end()) {
3740 keyCode = replacementIt->second;
3741 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003742 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3743 }
3744 }
3745}
3746
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3748#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3750 "policyFlags=0x%x, action=0x%x, "
3751 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3752 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3753 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3754 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755#endif
3756 if (!validateKeyEvent(args->action)) {
3757 return;
3758 }
3759
3760 uint32_t policyFlags = args->policyFlags;
3761 int32_t flags = args->flags;
3762 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003763 // InputDispatcher tracks and generates key repeats on behalf of
3764 // whatever notifies it, so repeatCount should always be set to 0
3765 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3767 policyFlags |= POLICY_FLAG_VIRTUAL;
3768 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 if (policyFlags & POLICY_FLAG_FUNCTION) {
3771 metaState |= AMETA_FUNCTION_ON;
3772 }
3773
3774 policyFlags |= POLICY_FLAG_TRUSTED;
3775
Michael Wright78f24442014-08-06 15:55:28 -07003776 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003777 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003778
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003780 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003781 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3782 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783
Michael Wright2b3c3302018-03-02 17:19:13 +00003784 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003786 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3787 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 bool needWake;
3792 { // acquire lock
3793 mLock.lock();
3794
3795 if (shouldSendKeyToInputFilterLocked(args)) {
3796 mLock.unlock();
3797
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003798 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3800 return; // event was consumed by the filter
3801 }
3802
3803 mLock.lock();
3804 }
3805
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003806 std::unique_ptr<KeyEntry> newEntry =
3807 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3808 args->displayId, policyFlags, args->action, flags,
3809 keyCode, args->scanCode, metaState, repeatCount,
3810 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003812 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 mLock.unlock();
3814 } // release lock
3815
3816 if (needWake) {
3817 mLooper->wake();
3818 }
3819}
3820
3821bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3822 return mInputFilterEnabled;
3823}
3824
3825void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3826#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003827 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3828 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003829 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3830 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003831 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003832 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3833 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3834 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3835 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 for (uint32_t i = 0; i < args->pointerCount; i++) {
3837 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003838 "x=%f, y=%f, pressure=%f, size=%f, "
3839 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3840 "orientation=%f",
3841 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3842 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3843 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3844 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3845 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3846 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3847 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3848 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3849 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3850 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 }
3852#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003853 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3854 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 return;
3856 }
3857
3858 uint32_t policyFlags = args->policyFlags;
3859 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003860
3861 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003862 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003863 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3864 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003865 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867
3868 bool needWake;
3869 { // acquire lock
3870 mLock.lock();
3871
3872 if (shouldSendMotionToInputFilterLocked(args)) {
3873 mLock.unlock();
3874
3875 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003876 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003877 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3878 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003879 args->metaState, args->buttonState, args->classification, transform,
3880 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003881 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3882 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3883 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
3885 policyFlags |= POLICY_FLAG_FILTERED;
3886 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3887 return; // event was consumed by the filter
3888 }
3889
3890 mLock.lock();
3891 }
3892
3893 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003894 std::unique_ptr<MotionEntry> newEntry =
3895 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3896 args->source, args->displayId, policyFlags,
3897 args->action, args->actionButton, args->flags,
3898 args->metaState, args->buttonState,
3899 args->classification, args->edgeFlags,
3900 args->xPrecision, args->yPrecision,
3901 args->xCursorPosition, args->yCursorPosition,
3902 args->downTime, args->pointerCount,
3903 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003905 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 mLock.unlock();
3907 } // release lock
3908
3909 if (needWake) {
3910 mLooper->wake();
3911 }
3912}
3913
Chris Yef59a2f42020-10-16 12:55:26 -07003914void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3915#if DEBUG_INBOUND_EVENT_DETAILS
3916 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3917 " sensorType=%s",
3918 args->id, args->eventTime, args->deviceId, args->source,
3919 NamedEnum::string(args->sensorType).c_str());
3920#endif
3921
3922 bool needWake;
3923 { // acquire lock
3924 mLock.lock();
3925
3926 // Just enqueue a new sensor event.
3927 std::unique_ptr<SensorEntry> newEntry =
3928 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3929 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3930 args->sensorType, args->accuracy,
3931 args->accuracyChanged, args->values);
3932
3933 needWake = enqueueInboundEventLocked(std::move(newEntry));
3934 mLock.unlock();
3935 } // release lock
3936
3937 if (needWake) {
3938 mLooper->wake();
3939 }
3940}
3941
Chris Yefb552902021-02-03 17:18:37 -08003942void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3943#if DEBUG_INBOUND_EVENT_DETAILS
3944 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3945 args->deviceId, args->isOn);
3946#endif
3947 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3948}
3949
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003951 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952}
3953
3954void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3955#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003956 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003957 "switchMask=0x%08x",
3958 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959#endif
3960
3961 uint32_t policyFlags = args->policyFlags;
3962 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003963 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964}
3965
3966void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3967#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003968 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3969 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970#endif
3971
3972 bool needWake;
3973 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003974 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003976 std::unique_ptr<DeviceResetEntry> newEntry =
3977 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3978 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 } // release lock
3980
3981 if (needWake) {
3982 mLooper->wake();
3983 }
3984}
3985
Prabir Pradhan7e186182020-11-10 13:56:45 -08003986void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3987#if DEBUG_INBOUND_EVENT_DETAILS
3988 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3989 args->enabled ? "true" : "false");
3990#endif
3991
Prabir Pradhan99987712020-11-10 18:43:05 -08003992 bool needWake;
3993 { // acquire lock
3994 std::scoped_lock _l(mLock);
3995 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3996 args->enabled);
3997 needWake = enqueueInboundEventLocked(std::move(entry));
3998 } // release lock
3999
4000 if (needWake) {
4001 mLooper->wake();
4002 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004003}
4004
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004005InputEventInjectionResult InputDispatcher::injectInputEvent(
4006 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4007 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008#if DEBUG_INBOUND_EVENT_DETAILS
4009 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004010 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4011 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004013 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
4015 policyFlags |= POLICY_FLAG_INJECTED;
4016 if (hasInjectionPermission(injectorPid, injectorUid)) {
4017 policyFlags |= POLICY_FLAG_TRUSTED;
4018 }
4019
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004020 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004021 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4022 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4023 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4024 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4025 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004026 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004027 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004028 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004029 }
4030
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004031 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004033 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004034 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4035 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004036 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004037 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004040 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004041 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4042 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4043 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004044 int32_t keyCode = incomingKey.getKeyCode();
4045 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004046 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004048 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004049 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004050 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4051 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4052 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4055 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004056 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004057
4058 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4059 android::base::Timer t;
4060 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4061 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4062 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4063 std::to_string(t.duration().count()).c_str());
4064 }
4065 }
4066
4067 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004068 std::unique_ptr<KeyEntry> injectedEntry =
4069 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004070 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004071 incomingKey.getDisplayId(), policyFlags, action,
4072 flags, keyCode, incomingKey.getScanCode(), metaState,
4073 incomingKey.getRepeatCount(),
4074 incomingKey.getDownTime());
4075 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004076 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 }
4078
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004080 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4081 int32_t action = motionEvent.getAction();
4082 size_t pointerCount = motionEvent.getPointerCount();
4083 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4084 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004085 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004086 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 }
4090
4091 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004092 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 android::base::Timer t;
4094 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4095 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4096 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4097 std::to_string(t.duration().count()).c_str());
4098 }
4099 }
4100
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004101 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4102 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4103 }
4104
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004105 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004106 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4107 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004109 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4110 resolvedDeviceId, motionEvent.getSource(),
4111 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004112 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004113 motionEvent.getButtonState(),
4114 motionEvent.getClassification(),
4115 motionEvent.getEdgeFlags(),
4116 motionEvent.getXPrecision(),
4117 motionEvent.getYPrecision(),
4118 motionEvent.getRawXCursorPosition(),
4119 motionEvent.getRawYCursorPosition(),
4120 motionEvent.getDownTime(), uint32_t(pointerCount),
4121 pointerProperties, samplePointerCoords,
4122 motionEvent.getXOffset(),
4123 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004124 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004125 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004126 sampleEventTimes += 1;
4127 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004128 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004129 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4130 resolvedDeviceId, motionEvent.getSource(),
4131 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004132 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004133 motionEvent.getMetaState(),
4134 motionEvent.getButtonState(),
4135 motionEvent.getClassification(),
4136 motionEvent.getEdgeFlags(),
4137 motionEvent.getXPrecision(),
4138 motionEvent.getYPrecision(),
4139 motionEvent.getRawXCursorPosition(),
4140 motionEvent.getRawYCursorPosition(),
4141 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004142 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004143 samplePointerCoords, motionEvent.getXOffset(),
4144 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004145 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004146 }
4147 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004150 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004151 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004152 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 }
4154
4155 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004156 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 injectionState->injectionIsAsync = true;
4158 }
4159
4160 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004161 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
4163 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004164 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004165 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004166 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 }
4168
4169 mLock.unlock();
4170
4171 if (needWake) {
4172 mLooper->wake();
4173 }
4174
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004175 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004177 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 if (syncMode == InputEventInjectionSync::NONE) {
4180 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 } else {
4182 for (;;) {
4183 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004184 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 break;
4186 }
4187
4188 nsecs_t remainingTimeout = endTime - now();
4189 if (remainingTimeout <= 0) {
4190#if DEBUG_INJECTION
4191 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004194 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 }
4197
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004198 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 }
4200
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004201 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4202 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 while (injectionState->pendingForegroundDispatches != 0) {
4204#if DEBUG_INJECTION
4205 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207#endif
4208 nsecs_t remainingTimeout = endTime - now();
4209 if (remainingTimeout <= 0) {
4210#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4212 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004214 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 break;
4216 }
4217
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004218 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 }
4220 }
4221 }
4222
4223 injectionState->release();
4224 } // release lock
4225
4226#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004227 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229#endif
4230
4231 return injectionResult;
4232}
4233
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004234std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004235 std::array<uint8_t, 32> calculatedHmac;
4236 std::unique_ptr<VerifiedInputEvent> result;
4237 switch (event.getType()) {
4238 case AINPUT_EVENT_TYPE_KEY: {
4239 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4240 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4241 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004242 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004243 break;
4244 }
4245 case AINPUT_EVENT_TYPE_MOTION: {
4246 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4247 VerifiedMotionEvent verifiedMotionEvent =
4248 verifiedMotionEventFromMotionEvent(motionEvent);
4249 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004250 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004251 break;
4252 }
4253 default: {
4254 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4255 return nullptr;
4256 }
4257 }
4258 if (calculatedHmac == INVALID_HMAC) {
4259 return nullptr;
4260 }
4261 if (calculatedHmac != event.getHmac()) {
4262 return nullptr;
4263 }
4264 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004265}
4266
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 return injectorUid == 0 ||
4269 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270}
4271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004272void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004273 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004274 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 if (injectionState) {
4276#if DEBUG_INJECTION
4277 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 "injectorPid=%d, injectorUid=%d",
4279 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280#endif
4281
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 // Log the outcome since the injector did not wait for the injection result.
4284 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004285 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 ALOGV("Asynchronous input event injection succeeded.");
4287 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004288 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 ALOGW("Asynchronous input event injection failed.");
4290 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004291 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004292 ALOGW("Asynchronous input event injection permission denied.");
4293 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004294 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 ALOGW("Asynchronous input event injection timed out.");
4296 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004297 case InputEventInjectionResult::PENDING:
4298 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4299 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301 }
4302
4303 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004304 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306}
4307
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004308void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4309 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 if (injectionState) {
4311 injectionState->pendingForegroundDispatches += 1;
4312 }
4313}
4314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004315void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4316 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 if (injectionState) {
4318 injectionState->pendingForegroundDispatches -= 1;
4319
4320 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004321 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323 }
4324}
4325
chaviw3277faf2021-05-19 16:45:23 -05004326const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004327 int32_t displayId) const {
chaviw3277faf2021-05-19 16:45:23 -05004328 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004329 auto it = mWindowHandlesByDisplay.find(displayId);
4330 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004331}
4332
chaviw3277faf2021-05-19 16:45:23 -05004333sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004334 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004335 if (windowHandleToken == nullptr) {
4336 return nullptr;
4337 }
4338
Arthur Hungb92218b2018-08-14 12:00:21 +08004339 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004340 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4341 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004342 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004343 return windowHandle;
4344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 }
4346 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004347 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348}
4349
chaviw3277faf2021-05-19 16:45:23 -05004350sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4351 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004352 if (windowHandleToken == nullptr) {
4353 return nullptr;
4354 }
4355
chaviw3277faf2021-05-19 16:45:23 -05004356 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004357 if (windowHandle->getToken() == windowHandleToken) {
4358 return windowHandle;
4359 }
4360 }
4361 return nullptr;
4362}
4363
chaviw3277faf2021-05-19 16:45:23 -05004364sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4365 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004366 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004367 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4368 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004369 if (handle->getId() == windowHandle->getId() &&
4370 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004371 if (windowHandle->getInfo()->displayId != it.first) {
4372 ALOGE("Found window %s in display %" PRId32
4373 ", but it should belong to display %" PRId32,
4374 windowHandle->getName().c_str(), it.first,
4375 windowHandle->getInfo()->displayId);
4376 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004377 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 }
4380 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004381 return nullptr;
4382}
4383
chaviw3277faf2021-05-19 16:45:23 -05004384sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004385 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4386 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387}
4388
chaviw3277faf2021-05-19 16:45:23 -05004389bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004390 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4391 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004392 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004393 if (connection != nullptr && noInputChannel) {
4394 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4395 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4396 return false;
4397 }
4398
4399 if (connection == nullptr) {
4400 if (!noInputChannel) {
4401 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4402 }
4403 return false;
4404 }
4405 if (!connection->responsive) {
4406 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4407 return false;
4408 }
4409 return true;
4410}
4411
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004412std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4413 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004414 auto connectionIt = mConnectionsByToken.find(token);
4415 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004416 return nullptr;
4417 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004418 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004419}
4420
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004421void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw3277faf2021-05-19 16:45:23 -05004422 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4423 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004424 // Remove all handles on a display if there are no windows left.
4425 mWindowHandlesByDisplay.erase(displayId);
4426 return;
4427 }
4428
4429 // Since we compare the pointer of input window handles across window updates, we need
4430 // to make sure the handle object for the same window stays unchanged across updates.
chaviw3277faf2021-05-19 16:45:23 -05004431 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4432 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4433 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004434 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004435 }
4436
chaviw3277faf2021-05-19 16:45:23 -05004437 std::vector<sp<WindowInfoHandle>> newHandles;
4438 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004439 if (!handle->updateInfo()) {
4440 // handle no longer valid
4441 continue;
4442 }
4443
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
Garfield Tane84e6f92019-08-29 17:28:41 -07006243} // namespace android::inputdispatcher