blob: 2988d9979272bd23e553115f126820563291d8c8 [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
liushenxiang42232912021-05-21 20:24:09 +08001267 // Reset key repeating in case a keyboard device was disabled or enabled.
1268 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1269 resetKeyRepeatLocked();
1270 }
1271
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 synthesizeCancelationEventsForAllConnectionsLocked(options);
1275 return true;
1276}
1277
Vishnu Nairad321cd2020-08-20 16:40:21 -07001278void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001279 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001280 if (mPendingEvent != nullptr) {
1281 // Move the pending event to the front of the queue. This will give the chance
1282 // for the pending event to get dispatched to the newly focused window
1283 mInboundQueue.push_front(mPendingEvent);
1284 mPendingEvent = nullptr;
1285 }
1286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 std::unique_ptr<FocusEntry> focusEntry =
1288 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1289 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001290
1291 // This event should go to the front of the queue, but behind all other focus events
1292 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001293 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001294 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 [](const std::shared_ptr<EventEntry>& event) {
1296 return event->type == EventEntry::Type::FOCUS;
1297 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001298
1299 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001301}
1302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001304 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001305 if (channel == nullptr) {
1306 return; // Window has gone away
1307 }
1308 InputTarget target;
1309 target.inputChannel = channel;
1310 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1311 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001312 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1313 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001314 std::string reason = std::string("reason=").append(entry->reason);
1315 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001316 dispatchEventLocked(currentTime, entry, {target});
1317}
1318
Prabir Pradhan99987712020-11-10 18:43:05 -08001319void InputDispatcher::dispatchPointerCaptureChangedLocked(
1320 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1321 DropReason& dropReason) {
1322 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001323 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1324 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1325 }
1326 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001327 // Pointer capture was already forcefully disabled because of focus change.
1328 dropReason = DropReason::NOT_DROPPED;
1329 return;
1330 }
1331
1332 // Set drop reason for early returns
1333 dropReason = DropReason::NO_POINTER_CAPTURE;
1334
1335 sp<IBinder> token;
1336 if (entry->pointerCaptureEnabled) {
1337 // Enable Pointer Capture
1338 if (!mFocusedWindowRequestedPointerCapture) {
1339 // This can happen if a window requests capture and immediately releases capture.
1340 ALOGW("No window requested Pointer Capture.");
1341 return;
1342 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001343 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001344 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1345 mWindowTokenWithPointerCapture = token;
1346 } else {
1347 // Disable Pointer Capture
1348 token = mWindowTokenWithPointerCapture;
1349 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001350 if (mFocusedWindowRequestedPointerCapture) {
1351 mFocusedWindowRequestedPointerCapture = false;
1352 setPointerCaptureLocked(false);
1353 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001354 }
1355
1356 auto channel = getInputChannelLocked(token);
1357 if (channel == nullptr) {
1358 // Window has gone away, clean up Pointer Capture state.
1359 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001360 if (mFocusedWindowRequestedPointerCapture) {
1361 mFocusedWindowRequestedPointerCapture = false;
1362 setPointerCaptureLocked(false);
1363 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001364 return;
1365 }
1366 InputTarget target;
1367 target.inputChannel = channel;
1368 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1369 entry->dispatchInProgress = true;
1370 dispatchEventLocked(currentTime, entry, {target});
1371
1372 dropReason = DropReason::NOT_DROPPED;
1373}
1374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001375bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001376 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001378 if (!entry->dispatchInProgress) {
1379 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1380 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1381 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1382 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001383 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 // We have seen two identical key downs in a row which indicates that the device
1385 // driver is automatically generating key repeats itself. We take note of the
1386 // repeat here, but we disable our own next key repeat timer since it is clear that
1387 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001388 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1389 // Make sure we don't get key down from a different device. If a different
1390 // device Id has same key pressed down, the new device Id will replace the
1391 // current one to hold the key repeat with repeat count reset.
1392 // In the future when got a KEY_UP on the device id, drop it and do not
1393 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1395 resetKeyRepeatLocked();
1396 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1397 } else {
1398 // Not a repeat. Save key down state in case we do see a repeat later.
1399 resetKeyRepeatLocked();
1400 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1401 }
1402 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001403 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1404 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001405 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001406#if DEBUG_INBOUND_EVENT_DETAILS
1407 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1408#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 resetKeyRepeatLocked();
1411 }
1412
1413 if (entry->repeatCount == 1) {
1414 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1415 } else {
1416 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1417 }
1418
1419 entry->dispatchInProgress = true;
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 }
1423
1424 // Handle case where the policy asked us to try again later last time.
1425 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1426 if (currentTime < entry->interceptKeyWakeupTime) {
1427 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1428 *nextWakeupTime = entry->interceptKeyWakeupTime;
1429 }
1430 return false; // wait until next wakeup
1431 }
1432 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1433 entry->interceptKeyWakeupTime = 0;
1434 }
1435
1436 // Give the policy a chance to intercept the key.
1437 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1438 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001439 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001440 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001441 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001442 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001443 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001445 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 return false; // wait for the command to run
1447 } else {
1448 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1449 }
1450 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001451 if (*dropReason == DropReason::NOT_DROPPED) {
1452 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454 }
1455
1456 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001457 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001458 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001459 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1460 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001461 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 return true;
1463 }
1464
1465 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001466 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001469 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 return false;
1471 }
1472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return true;
1476 }
1477
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001478 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
1481 // Dispatch the key.
1482 dispatchEventLocked(currentTime, entry, inputTargets);
1483 return true;
1484}
1485
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001486void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001488 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001489 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1490 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001491 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1492 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1493 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494#endif
1495}
1496
Chris Yef59a2f42020-10-16 12:55:26 -07001497void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1498 mLock.unlock();
1499
1500 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1501 if (entry->accuracyChanged) {
1502 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1503 }
1504 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1505 entry->hwTimestamp, entry->values);
1506 mLock.lock();
1507}
1508
1509void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1510 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1511#if DEBUG_OUTBOUND_EVENT_DETAILS
1512 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1513 "source=0x%x, sensorType=%s",
1514 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001515 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001516#endif
1517 std::unique_ptr<CommandEntry> commandEntry =
1518 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1519 commandEntry->sensorEntry = entry;
1520 postCommandLocked(std::move(commandEntry));
1521}
1522
1523bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1524#if DEBUG_OUTBOUND_EVENT_DETAILS
1525 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1526 NamedEnum::string(sensorType).c_str());
1527#endif
1528 { // acquire lock
1529 std::scoped_lock _l(mLock);
1530
1531 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1532 std::shared_ptr<EventEntry> entry = *it;
1533 if (entry->type == EventEntry::Type::SENSOR) {
1534 it = mInboundQueue.erase(it);
1535 releaseInboundEventLocked(entry);
1536 }
1537 }
1538 }
1539 return true;
1540}
1541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001542bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001543 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001544 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001546 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 entry->dispatchInProgress = true;
1548
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551
1552 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001553 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1556 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return true;
1558 }
1559
1560 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1561
1562 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001563 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564
1565 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 if (isPointerEvent) {
1568 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001570 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001571 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 } else {
1573 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001574 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 return false;
1579 }
1580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001583 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1584 return true;
1585 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001587 CancelationOptions::Mode mode(isPointerEvent
1588 ? CancelationOptions::CANCEL_POINTER_EVENTS
1589 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1590 CancelationOptions options(mode, "input event injection failed");
1591 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 return true;
1593 }
1594
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001595 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001596 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001598 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001599 std::unordered_map<int32_t, TouchState>::iterator it =
1600 mTouchStatesByDisplay.find(entry->displayId);
1601 if (it != mTouchStatesByDisplay.end()) {
1602 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001603 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001604 // The event has gone through these portal windows, so we add monitoring targets of
1605 // the corresponding displays as well.
1606 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05001607 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001608 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001609 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001610 }
1611 }
1612 }
1613 }
1614
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 // Dispatch the motion.
1616 if (conflictingPointerActions) {
1617 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 synthesizeCancelationEventsForAllConnectionsLocked(options);
1620 }
1621 dispatchEventLocked(currentTime, entry, inputTargets);
1622 return true;
1623}
1624
chaviw3277faf2021-05-19 16:45:23 -05001625void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001626 bool isExiting, const MotionEntry& motionEntry) {
1627 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1628 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1629 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1630 PointerCoords pointerCoords;
1631 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1632 pointerCoords.transform(windowHandle->getInfo()->transform);
1633
1634 std::unique_ptr<DragEntry> dragEntry =
1635 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1636 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1637 pointerCoords.getY());
1638
1639 enqueueInboundEventLocked(std::move(dragEntry));
1640}
1641
1642void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1643 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1644 if (channel == nullptr) {
1645 return; // Window has gone away
1646 }
1647 InputTarget target;
1648 target.inputChannel = channel;
1649 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1650 entry->dispatchInProgress = true;
1651 dispatchEventLocked(currentTime, entry, {target});
1652}
1653
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001656 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 ", policyFlags=0x%x, "
1658 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1659 "metaState=0x%x, buttonState=0x%x,"
1660 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001661 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1662 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1663 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001665 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001667 "x=%f, y=%f, pressure=%f, size=%f, "
1668 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1669 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1671 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1672 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1673 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1674 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1675 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1676 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1677 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1678 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1679 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 }
1681#endif
1682}
1683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001684void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1685 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001686 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001687 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688#if DEBUG_DISPATCH_CYCLE
1689 ALOGD("dispatchEventToCurrentInputTargets");
1690#endif
1691
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001692 updateInteractionTokensLocked(*eventEntry, inputTargets);
1693
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001698 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001699 sp<Connection> connection =
1700 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001701 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001702 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001704 if (DEBUG_FOCUS) {
1705 ALOGD("Dropping event delivery to target with channel '%s' because it "
1706 "is no longer registered with the input dispatcher.",
1707 inputTarget.inputChannel->getName().c_str());
1708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 }
1710 }
1711}
1712
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001713void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1714 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1715 // If the policy decides to close the app, we will get a channel removal event via
1716 // unregisterInputChannel, and will clean up the connection that way. We are already not
1717 // sending new pointers to the connection when it blocked, but focused events will continue to
1718 // pile up.
1719 ALOGW("Canceling events for %s because it is unresponsive",
1720 connection->inputChannel->getName().c_str());
1721 if (connection->status == Connection::STATUS_NORMAL) {
1722 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1723 "application not responding");
1724 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
1726}
1727
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001728void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001729 if (DEBUG_FOCUS) {
1730 ALOGD("Resetting ANR timeouts.");
1731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732
1733 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001734 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001735 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736}
1737
Tiger Huang721e26f2018-07-24 22:26:19 +08001738/**
1739 * Get the display id that the given event should go to. If this event specifies a valid display id,
1740 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1741 * Focused display is the display that the user most recently interacted with.
1742 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001743int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001744 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001745 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001746 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001747 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1748 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 break;
1750 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001751 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001752 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1753 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 break;
1755 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001756 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001757 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001758 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001759 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001760 case EventEntry::Type::SENSOR:
1761 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001762 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001763 return ADISPLAY_ID_NONE;
1764 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001765 }
1766 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1767}
1768
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001769bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1770 const char* focusedWindowName) {
1771 if (mAnrTracker.empty()) {
1772 // already processed all events that we waited for
1773 mKeyIsWaitingForEventsTimeout = std::nullopt;
1774 return false;
1775 }
1776
1777 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1778 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001779 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001780 mKeyIsWaitingForEventsTimeout = currentTime +
1781 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1782 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001783 return true;
1784 }
1785
1786 // We still have pending events, and already started the timer
1787 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1788 return true; // Still waiting
1789 }
1790
1791 // Waited too long, and some connection still hasn't processed all motions
1792 // Just send the key to the focused window
1793 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1794 focusedWindowName);
1795 mKeyIsWaitingForEventsTimeout = std::nullopt;
1796 return false;
1797}
1798
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001799InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1800 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1801 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001802 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803
Tiger Huang721e26f2018-07-24 22:26:19 +08001804 int32_t displayId = getTargetDisplayId(entry);
chaviw3277faf2021-05-19 16:45:23 -05001805 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001806 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001807 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1808
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 // If there is no currently focused window and no focused application
1810 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001811 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1812 ALOGI("Dropping %s event because there is no focused window or focused application in "
1813 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001814 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
1817
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1819 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1820 // start interacting with another application via touch (app switch). This code can be removed
1821 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1822 // an app is expected to have a focused window.
1823 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1824 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1825 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001826 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1827 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1828 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001830 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831 ALOGW("Waiting because no window has focus but %s may eventually add a "
1832 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001833 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001834 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1837 // Already raised ANR. Drop the event
1838 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001839 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 } else {
1842 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001844 }
1845 }
1846
1847 // we have a valid, non-null focused window
1848 resetNoFocusedWindowTimeoutLocked();
1849
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
1854
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001855 if (focusedWindowHandle->getInfo()->paused) {
1856 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001858 }
1859
1860 // If the event is a key event, then we must wait for all previous events to
1861 // complete before delivering it because previous events may have the
1862 // side-effect of transferring focus to a different window and we want to
1863 // ensure that the following keys are sent to the new window.
1864 //
1865 // Suppose the user touches a button in a window then immediately presses "A".
1866 // If the button causes a pop-up window to appear then we want to ensure that
1867 // the "A" key is delivered to the new pop-up window. This is because users
1868 // often anticipate pending UI changes when typing on a keyboard.
1869 // To obtain this behavior, we must serialize key events with respect to all
1870 // prior input events.
1871 if (entry.type == EventEntry::Type::KEY) {
1872 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1873 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
1877
1878 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001879 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1881 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882
1883 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885}
1886
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887/**
1888 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1889 * that are currently unresponsive.
1890 */
1891std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1892 const std::vector<TouchedMonitor>& monitors) const {
1893 std::vector<TouchedMonitor> responsiveMonitors;
1894 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1895 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1896 sp<Connection> connection = getConnectionLocked(
1897 monitor.monitor.inputChannel->getConnectionToken());
1898 if (connection == nullptr) {
1899 ALOGE("Could not find connection for monitor %s",
1900 monitor.monitor.inputChannel->getName().c_str());
1901 return false;
1902 }
1903 if (!connection->responsive) {
1904 ALOGW("Unresponsive monitor %s will not get the new gesture",
1905 connection->inputChannel->getName().c_str());
1906 return false;
1907 }
1908 return true;
1909 });
1910 return responsiveMonitors;
1911}
1912
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001913InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1914 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1915 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 enum InjectionPermission {
1918 INJECTION_PERMISSION_UNKNOWN,
1919 INJECTION_PERMISSION_GRANTED,
1920 INJECTION_PERMISSION_DENIED
1921 };
1922
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 // For security reasons, we defer updating the touch state until we are sure that
1924 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001925 int32_t displayId = entry.displayId;
1926 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1928
1929 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001930 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw3277faf2021-05-19 16:45:23 -05001932 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1933 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001935 // Copy current touch state into tempTouchState.
1936 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1937 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001938 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001940 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1941 mTouchStatesByDisplay.find(displayId);
1942 if (oldStateIt != mTouchStatesByDisplay.end()) {
1943 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001945 }
1946
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 bool isSplit = tempTouchState.split;
1948 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1949 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1950 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001951 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1952 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1953 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1954 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1955 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001956 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 bool wrongDevice = false;
1958 if (newGesture) {
1959 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001960 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001961 ALOGI("Dropping event because a pointer for a different device is already down "
1962 "in display %" PRId32,
1963 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001964 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 switchedDevice = false;
1967 wrongDevice = true;
1968 goto Failed;
1969 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001970 tempTouchState.reset();
1971 tempTouchState.down = down;
1972 tempTouchState.deviceId = entry.deviceId;
1973 tempTouchState.source = entry.source;
1974 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001976 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001977 ALOGI("Dropping move event because a pointer for a different device is already active "
1978 "in display %" PRId32,
1979 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001980 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001981 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001982 switchedDevice = false;
1983 wrongDevice = true;
1984 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
1986
1987 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1988 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1989
Garfield Tan00f511d2019-06-12 16:55:40 -07001990 int32_t x;
1991 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001993 // Always dispatch mouse events to cursor position.
1994 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001995 x = int32_t(entry.xCursorPosition);
1996 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001997 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001998 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1999 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002000 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002001 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07002002 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2004 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002005
2006 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002007 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002008 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002011 if (newTouchedWindowHandle != nullptr &&
2012 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002013 // New window supports splitting, but we should never split mouse events.
2014 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 } else if (isSplit) {
2016 // New window does not support splitting but we have already split events.
2017 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002018 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
2020
2021 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002022 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002024 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002025 }
2026
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2028 ALOGI("Not sending touch event to %s because it is paused",
2029 newTouchedWindowHandle->getName().c_str());
2030 newTouchedWindowHandle = nullptr;
2031 }
2032
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002033 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002034 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002035 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2036 if (!isResponsive) {
2037 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2039 newTouchedWindowHandle = nullptr;
2040 }
2041 }
2042
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002043 // Drop events that can't be trusted due to occlusion
2044 if (newTouchedWindowHandle != nullptr &&
2045 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2046 TouchOcclusionInfo occlusionInfo =
2047 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002048 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002049 if (DEBUG_TOUCH_OCCLUSION) {
2050 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2051 for (const auto& log : occlusionInfo.debugInfo) {
2052 ALOGD("%s", log.c_str());
2053 }
2054 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002055 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2056 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2057 ALOGW("Dropping untrusted touch event due to %s/%d",
2058 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2059 newTouchedWindowHandle = nullptr;
2060 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002061 }
2062 }
2063
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064 // Also don't send the new touch event to unresponsive gesture monitors
2065 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2066
Michael Wright3dd60e22019-03-27 22:06:44 +00002067 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2068 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 "(%d, %d) in display %" PRId32 ".",
2070 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002071 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 goto Failed;
2073 }
2074
2075 if (newTouchedWindowHandle != nullptr) {
2076 // Set target flags.
2077 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2078 if (isSplit) {
2079 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2082 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2083 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2084 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2085 }
2086
2087 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002088 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2089 newHoverWindowHandle = nullptr;
2090 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002091 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002092 }
2093
2094 // Update the temporary touch state.
2095 BitSet32 pointerIds;
2096 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002097 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002098 pointerIds.markBit(pointerId);
2099 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002103 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 } else {
2105 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2106
2107 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002108 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002109 if (DEBUG_FOCUS) {
2110 ALOGD("Dropping event because the pointer is not down or we previously "
2111 "dropped the pointer down event in display %" PRId32,
2112 displayId);
2113 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002114 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 goto Failed;
2116 }
2117
arthurhung6d4bed92021-03-17 11:59:33 +08002118 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002119
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002121 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2124 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
chaviw3277faf2021-05-19 16:45:23 -05002126 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002128 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002129 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2130 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002131 if (DEBUG_FOCUS) {
2132 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2133 oldTouchedWindowHandle->getName().c_str(),
2134 newTouchedWindowHandle->getName().c_str(), displayId);
2135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002137 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2138 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2139 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
2141 // Make a slippery entrance into the new window.
2142 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2143 isSplit = true;
2144 }
2145
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002146 int32_t targetFlags =
2147 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 if (isSplit) {
2149 targetFlags |= InputTarget::FLAG_SPLIT;
2150 }
2151 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2152 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002153 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2154 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156
2157 BitSet32 pointerIds;
2158 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002161 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
2163 }
2164 }
2165
2166 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002167 // Let the previous window know that the hover sequence is over, unless we already did it
2168 // when dispatching it as is to newTouchedWindowHandle.
2169 if (mLastHoverWindowHandle != nullptr &&
2170 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2171 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172#if DEBUG_HOVER
2173 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2177 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 }
2179
Garfield Tandf26e862020-07-01 20:18:19 -07002180 // Let the new window know that the hover sequence is starting, unless we already did it
2181 // when dispatching it as is to newTouchedWindowHandle.
2182 if (newHoverWindowHandle != nullptr &&
2183 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2184 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185#if DEBUG_HOVER
2186 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002187 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2190 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2191 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
2193 }
2194
2195 // Check permission to inject into all touched foreground windows and ensure there
2196 // is at least one touched foreground window.
2197 {
2198 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002199 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2201 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002202 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002203 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 injectionPermission = INJECTION_PERMISSION_DENIED;
2205 goto Failed;
2206 }
2207 }
2208 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002209 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002210 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002211 ALOGI("Dropping event because there is no touched foreground window in display "
2212 "%" PRId32 " or gesture monitor to receive it.",
2213 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002214 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 goto Failed;
2216 }
2217
2218 // Permission granted to injection into all touched foreground windows.
2219 injectionPermission = INJECTION_PERMISSION_GRANTED;
2220 }
2221
2222 // Check whether windows listening for outside touches are owned by the same UID. If it is
2223 // set the policy flag that we will not reveal coordinate information to this window.
2224 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002225 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002226 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002227 if (foregroundWindowHandle) {
2228 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw3277faf2021-05-19 16:45:23 -05002231 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2232 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2233 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002234 InputTarget::FLAG_ZERO_COORDS,
2235 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
2238 }
2239 }
2240 }
2241
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // If this is the first pointer going down and the touched window has a wallpaper
2243 // then also add the touched wallpaper windows so they are locked in for the duration
2244 // of the touch gesture.
2245 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2246 // engine only supports touch events. We would need to add a mechanism similar
2247 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2248 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002249 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002251 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw3277faf2021-05-19 16:45:23 -05002252 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002253 getWindowHandlesLocked(displayId);
chaviw3277faf2021-05-19 16:45:23 -05002254 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2255 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 if (info->displayId == displayId &&
chaviw3277faf2021-05-19 16:45:23 -05002257 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002258 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 .addOrUpdateWindow(windowHandle,
2260 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2261 InputTarget::
2262 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2263 InputTarget::FLAG_DISPATCH_AS_IS,
2264 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266 }
2267 }
2268 }
2269
2270 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002271 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002273 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002279 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002281 }
2282
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 // Drop the outside or hover touch windows since we will not care about them
2284 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002285 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287Failed:
2288 // Check injection permission once and for all.
2289 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002290 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 injectionPermission = INJECTION_PERMISSION_GRANTED;
2292 } else {
2293 injectionPermission = INJECTION_PERMISSION_DENIED;
2294 }
2295 }
2296
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002297 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2298 return injectionResult;
2299 }
2300
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002302 if (!wrongDevice) {
2303 if (switchedDevice) {
2304 if (DEBUG_FOCUS) {
2305 ALOGD("Conflicting pointer actions: Switched to a different device.");
2306 }
2307 *outConflictingPointerActions = true;
2308 }
2309
2310 if (isHoverAction) {
2311 // Started hovering, therefore no longer down.
2312 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002313 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002314 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2315 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 *outConflictingPointerActions = true;
2318 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002319 tempTouchState.reset();
2320 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2321 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2322 tempTouchState.deviceId = entry.deviceId;
2323 tempTouchState.source = entry.source;
2324 tempTouchState.displayId = displayId;
2325 }
2326 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2327 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2328 // All pointers up or canceled.
2329 tempTouchState.reset();
2330 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2331 // First pointer went down.
2332 if (oldState && oldState->down) {
2333 if (DEBUG_FOCUS) {
2334 ALOGD("Conflicting pointer actions: Down received while already down.");
2335 }
2336 *outConflictingPointerActions = true;
2337 }
2338 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2339 // One pointer went up.
2340 if (isSplit) {
2341 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2342 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002344 for (size_t i = 0; i < tempTouchState.windows.size();) {
2345 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2346 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2347 touchedWindow.pointerIds.clearBit(pointerId);
2348 if (touchedWindow.pointerIds.isEmpty()) {
2349 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2350 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002353 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002355 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002356 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002357
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 // Save changes unless the action was scroll in which case the temporary touch
2359 // state was only valid for this one action.
2360 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2361 if (tempTouchState.displayId >= 0) {
2362 mTouchStatesByDisplay[displayId] = tempTouchState;
2363 } else {
2364 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002368 // Update hover state.
2369 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 return injectionResult;
2373}
2374
arthurhung6d4bed92021-03-17 11:59:33 +08002375void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw3277faf2021-05-19 16:45:23 -05002376 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002377 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2378 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2379 true /*ignoreDragWindow*/);
2380 if (dropWindow) {
2381 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2382 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002383 } else {
2384 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002385 }
2386 mDragState.reset();
2387}
2388
2389void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2390 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002391 return;
2392 }
2393
arthurhung6d4bed92021-03-17 11:59:33 +08002394 if (!mDragState->isStartDrag) {
2395 mDragState->isStartDrag = true;
2396 mDragState->isStylusButtonDownAtStart =
2397 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2398 }
2399
arthurhungb89ccb02020-12-30 16:19:01 +08002400 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2401 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2402 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2403 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002404 // Handle the special case : stylus button no longer pressed.
2405 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2406 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2407 finishDragAndDrop(entry.displayId, x, y);
2408 return;
2409 }
2410
chaviw3277faf2021-05-19 16:45:23 -05002411 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002412 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002413 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2414 true /*ignoreDragWindow*/);
2415 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002416 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2417 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2418 if (mDragState->dragHoverWindowHandle != nullptr) {
2419 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2420 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002421 }
arthurhung6d4bed92021-03-17 11:59:33 +08002422 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002423 }
2424 // enqueue drag location if needed.
2425 if (hoverWindowHandle != nullptr) {
2426 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2427 }
arthurhung6d4bed92021-03-17 11:59:33 +08002428 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2429 finishDragAndDrop(entry.displayId, x, y);
2430 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002431 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002432 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002433 }
2434}
2435
chaviw3277faf2021-05-19 16:45:23 -05002436void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002437 int32_t targetFlags, BitSet32 pointerIds,
2438 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439 std::vector<InputTarget>::iterator it =
2440 std::find_if(inputTargets.begin(), inputTargets.end(),
2441 [&windowHandle](const InputTarget& inputTarget) {
2442 return inputTarget.inputChannel->getConnectionToken() ==
2443 windowHandle->getToken();
2444 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002445
chaviw3277faf2021-05-19 16:45:23 -05002446 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002447
2448 if (it == inputTargets.end()) {
2449 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002450 std::shared_ptr<InputChannel> inputChannel =
2451 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002452 if (inputChannel == nullptr) {
2453 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2454 return;
2455 }
2456 inputTarget.inputChannel = inputChannel;
2457 inputTarget.flags = targetFlags;
2458 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002459 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002460 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002461 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002462 inputTargets.push_back(inputTarget);
2463 it = inputTargets.end() - 1;
2464 }
2465
2466 ALOG_ASSERT(it->flags == targetFlags);
2467 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2468
chaviw1ff3d1e2020-07-01 15:53:47 -07002469 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470}
2471
Michael Wright3dd60e22019-03-27 22:06:44 +00002472void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 int32_t displayId, float xOffset,
2474 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002475 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2476 mGlobalMonitorsByDisplay.find(displayId);
2477
2478 if (it != mGlobalMonitorsByDisplay.end()) {
2479 const std::vector<Monitor>& monitors = it->second;
2480 for (const Monitor& monitor : monitors) {
2481 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484}
2485
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2487 float yOffset,
2488 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002489 InputTarget target;
2490 target.inputChannel = monitor.inputChannel;
2491 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002492 ui::Transform t;
2493 t.set(xOffset, yOffset);
2494 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002495 inputTargets.push_back(target);
2496}
2497
chaviw3277faf2021-05-19 16:45:23 -05002498bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499 const InjectionState* injectionState) {
2500 if (injectionState &&
2501 (windowHandle == nullptr ||
2502 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2503 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002504 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 "owned by uid %d",
2507 injectionState->injectorPid, injectionState->injectorUid,
2508 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 } else {
2510 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
2513 return false;
2514 }
2515 return true;
2516}
2517
Robert Carrc9bf1d32020-04-13 17:21:08 -07002518/**
2519 * Indicate whether one window handle should be considered as obscuring
2520 * another window handle. We only check a few preconditions. Actually
2521 * checking the bounds is left to the caller.
2522 */
chaviw3277faf2021-05-19 16:45:23 -05002523static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2524 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002525 // Compare by token so cloned layers aren't counted
2526 if (haveSameToken(windowHandle, otherHandle)) {
2527 return false;
2528 }
2529 auto info = windowHandle->getInfo();
2530 auto otherInfo = otherHandle->getInfo();
2531 if (!otherInfo->visible) {
2532 return false;
chaviw3277faf2021-05-19 16:45:23 -05002533 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002534 // Those act as if they were invisible, so we don't need to flag them.
2535 // We do want to potentially flag touchable windows even if they have 0
2536 // opacity, since they can consume touches and alter the effects of the
2537 // user interaction (eg. apps that rely on
2538 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2539 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2540 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002541 } else if (info->ownerUid == otherInfo->ownerUid) {
2542 // If ownerUid is the same we don't generate occlusion events as there
2543 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002544 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002545 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002546 return false;
2547 } else if (otherInfo->displayId != info->displayId) {
2548 return false;
2549 }
2550 return true;
2551}
2552
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002553/**
2554 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2555 * untrusted, one should check:
2556 *
2557 * 1. If result.hasBlockingOcclusion is true.
2558 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2559 * BLOCK_UNTRUSTED.
2560 *
2561 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2562 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2563 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2564 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2565 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2566 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2567 *
2568 * If neither of those is true, then it means the touch can be allowed.
2569 */
2570InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw3277faf2021-05-19 16:45:23 -05002571 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2572 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002573 int32_t displayId = windowInfo->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002574 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002575 TouchOcclusionInfo info;
2576 info.hasBlockingOcclusion = false;
2577 info.obscuringOpacity = 0;
2578 info.obscuringUid = -1;
2579 std::map<int32_t, float> opacityByUid;
chaviw3277faf2021-05-19 16:45:23 -05002580 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002581 if (windowHandle == otherHandle) {
2582 break; // All future windows are below us. Exit early.
2583 }
chaviw3277faf2021-05-19 16:45:23 -05002584 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002585 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2586 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002587 if (DEBUG_TOUCH_OCCLUSION) {
2588 info.debugInfo.push_back(
2589 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2590 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002591 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2592 // we perform the checks below to see if the touch can be propagated or not based on the
2593 // window's touch occlusion mode
2594 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2595 info.hasBlockingOcclusion = true;
2596 info.obscuringUid = otherInfo->ownerUid;
2597 info.obscuringPackage = otherInfo->packageName;
2598 break;
2599 }
2600 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2601 uint32_t uid = otherInfo->ownerUid;
2602 float opacity =
2603 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2604 // Given windows A and B:
2605 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2606 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2607 opacityByUid[uid] = opacity;
2608 if (opacity > info.obscuringOpacity) {
2609 info.obscuringOpacity = opacity;
2610 info.obscuringUid = uid;
2611 info.obscuringPackage = otherInfo->packageName;
2612 }
2613 }
2614 }
2615 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002616 if (DEBUG_TOUCH_OCCLUSION) {
2617 info.debugInfo.push_back(
2618 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2619 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002620 return info;
2621}
2622
chaviw3277faf2021-05-19 16:45:23 -05002623std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002624 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002625 return StringPrintf(INDENT2
2626 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2627 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2628 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2629 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002630 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002631 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002632 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002633 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2634 info->frameTop, info->frameRight, info->frameBottom,
2635 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002636 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2637 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2638 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002639}
2640
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002641bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2642 if (occlusionInfo.hasBlockingOcclusion) {
2643 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2644 occlusionInfo.obscuringUid);
2645 return false;
2646 }
2647 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2648 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2649 "%.2f, maximum allowed = %.2f)",
2650 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2651 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2652 return false;
2653 }
2654 return true;
2655}
2656
chaviw3277faf2021-05-19 16:45:23 -05002657bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002660 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2661 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002662 if (windowHandle == otherHandle) {
2663 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 }
chaviw3277faf2021-05-19 16:45:23 -05002665 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002666 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002667 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 return true;
2669 }
2670 }
2671 return false;
2672}
2673
chaviw3277faf2021-05-19 16:45:23 -05002674bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002675 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002676 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2677 const WindowInfo* windowInfo = windowHandle->getInfo();
2678 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002679 if (windowHandle == otherHandle) {
2680 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002681 }
chaviw3277faf2021-05-19 16:45:23 -05002682 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002684 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002685 return true;
2686 }
2687 }
2688 return false;
2689}
2690
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002691std::string InputDispatcher::getApplicationWindowLabel(
chaviw3277faf2021-05-19 16:45:23 -05002692 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002693 if (applicationHandle != nullptr) {
2694 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002695 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 } else {
2697 return applicationHandle->getName();
2698 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002699 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002700 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002702 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 }
2704}
2705
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002706void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002707 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002708 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2709 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002710 // Focus or pointer capture changed events are passed to apps, but do not represent user
2711 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002712 return;
2713 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002714 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw3277faf2021-05-19 16:45:23 -05002715 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002716 if (focusedWindowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05002717 const WindowInfo* info = focusedWindowHandle->getInfo();
2718 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002720 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721#endif
2722 return;
2723 }
2724 }
2725
2726 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002727 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002728 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002729 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2730 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731 return;
2732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002734 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 eventType = USER_ACTIVITY_EVENT_TOUCH;
2736 }
2737 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002739 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002740 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2741 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 return;
2743 }
2744 eventType = USER_ACTIVITY_EVENT_BUTTON;
2745 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002747 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002748 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002749 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002750 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002751 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2752 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002753 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002754 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002755 break;
2756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 }
2758
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002759 std::unique_ptr<CommandEntry> commandEntry =
2760 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002761 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002763 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002764 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765}
2766
2767void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002768 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002769 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002770 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002771 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002772 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002773 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002774 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002775 ATRACE_NAME(message.c_str());
2776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777#if DEBUG_DISPATCH_CYCLE
2778 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002779 "globalScaleFactor=%f, pointerIds=0x%x %s",
2780 connection->getInputChannelName().c_str(), inputTarget.flags,
2781 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2782 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783#endif
2784
2785 // Skip this event if the connection status is not normal.
2786 // We don't want to enqueue additional outbound events if the connection is broken.
2787 if (connection->status != Connection::STATUS_NORMAL) {
2788#if DEBUG_DISPATCH_CYCLE
2789 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791#endif
2792 return;
2793 }
2794
2795 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002796 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2797 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2798 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002799 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002801 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002802 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002803 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002804 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 if (!splitMotionEntry) {
2806 return; // split event was dropped
2807 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002808 if (DEBUG_FOCUS) {
2809 ALOGD("channel '%s' ~ Split motion event.",
2810 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002811 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002812 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002813 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2814 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 return;
2816 }
2817 }
2818
2819 // Not splitting. Enqueue dispatch entries for the event as is.
2820 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2821}
2822
2823void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002825 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002826 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002827 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002829 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002830 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002831 ATRACE_NAME(message.c_str());
2832 }
2833
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002834 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835
2836 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002837 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002839 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002841 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002842 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002843 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002845 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002847 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
2850 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002851 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 startDispatchCycleLocked(currentTime, connection);
2853 }
2854}
2855
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002856void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002857 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002858 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002859 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002860 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2862 connection->getInputChannelName().c_str(),
2863 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002864 ATRACE_NAME(message.c_str());
2865 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002866 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 if (!(inputTargetFlags & dispatchMode)) {
2868 return;
2869 }
2870 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2871
2872 // This is a new event.
2873 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002874 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002875 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002877 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2878 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002879 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002881 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002882 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002883 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002884 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002885 dispatchEntry->resolvedAction = keyEntry.action;
2886 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2889 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2892 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 return; // skip the inconsistent event
2895 }
2896 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002899 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002900 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002901 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2902 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2903 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2904 static_cast<int32_t>(IdGenerator::Source::OTHER);
2905 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002906 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2907 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2908 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2909 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2910 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2911 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2912 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2913 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2914 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2915 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2916 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002917 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002918 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 }
2920 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002921 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2922 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2925 "event",
2926 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002928 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2929 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002933 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2935 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2936 }
2937 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2938 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2942 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2945 "event",
2946 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 return; // skip the inconsistent event
2949 }
2950
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002951 dispatchEntry->resolvedEventId =
2952 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2953 ? mIdGenerator.nextId()
2954 : motionEntry.id;
2955 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2956 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2957 ") to MotionEvent(id=0x%" PRIx32 ").",
2958 motionEntry.id, dispatchEntry->resolvedEventId);
2959 ATRACE_NAME(message.c_str());
2960 }
2961
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002962 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2963 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2964 // Skip reporting pointer down outside focus to the policy.
2965 break;
2966 }
2967
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002968 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002969 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970
2971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002973 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002974 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2975 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002976 break;
2977 }
Chris Yef59a2f42020-10-16 12:55:26 -07002978 case EventEntry::Type::SENSOR: {
2979 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2980 break;
2981 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002982 case EventEntry::Type::CONFIGURATION_CHANGED:
2983 case EventEntry::Type::DEVICE_RESET: {
2984 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002985 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002986 break;
2987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
2989
2990 // Remember that we are waiting for this dispatch to complete.
2991 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002992 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 }
2994
2995 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002996 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002997 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002998}
2999
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003000/**
3001 * This function is purely for debugging. It helps us understand where the user interaction
3002 * was taking place. For example, if user is touching launcher, we will see a log that user
3003 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3004 * We will see both launcher and wallpaper in that list.
3005 * Once the interaction with a particular set of connections starts, no new logs will be printed
3006 * until the set of interacted connections changes.
3007 *
3008 * The following items are skipped, to reduce the logspam:
3009 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3010 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3011 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3012 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3013 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003014 */
3015void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3016 const std::vector<InputTarget>& targets) {
3017 // Skip ACTION_UP events, and all events other than keys and motions
3018 if (entry.type == EventEntry::Type::KEY) {
3019 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3020 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3021 return;
3022 }
3023 } else if (entry.type == EventEntry::Type::MOTION) {
3024 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3025 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3026 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3027 return;
3028 }
3029 } else {
3030 return; // Not a key or a motion
3031 }
3032
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003033 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003034 std::vector<sp<Connection>> newConnections;
3035 for (const InputTarget& target : targets) {
3036 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3037 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3038 continue; // Skip windows that receive ACTION_OUTSIDE
3039 }
3040
3041 sp<IBinder> token = target.inputChannel->getConnectionToken();
3042 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003043 if (connection == nullptr) {
3044 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003045 }
3046 newConnectionTokens.insert(std::move(token));
3047 newConnections.emplace_back(connection);
3048 }
3049 if (newConnectionTokens == mInteractionConnectionTokens) {
3050 return; // no change
3051 }
3052 mInteractionConnectionTokens = newConnectionTokens;
3053
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003054 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003055 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003056 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003057 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003058 std::string message = "Interaction with: " + targetList;
3059 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003060 message += "<none>";
3061 }
3062 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3063}
3064
chaviwfd6d3512019-03-25 13:23:49 -07003065void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003066 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003067 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003068 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3069 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003070 return;
3071 }
3072
Vishnu Nairc519ff72021-01-21 08:23:08 -08003073 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003074 if (focusedToken == token) {
3075 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003076 return;
3077 }
3078
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003079 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3080 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003081 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003082 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083}
3084
3085void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003087 if (ATRACE_ENABLED()) {
3088 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003090 ATRACE_NAME(message.c_str());
3091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094#endif
3095
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003096 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3097 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003099 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003100 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003101 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
3103 // Publish the event.
3104 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3106 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003107 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3109 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003112 status = connection->inputPublisher
3113 .publishKeyEvent(dispatchEntry->seq,
3114 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3115 keyEntry.source, keyEntry.displayId,
3116 std::move(hmac), dispatchEntry->resolvedAction,
3117 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3118 keyEntry.scanCode, keyEntry.metaState,
3119 keyEntry.repeatCount, keyEntry.downTime,
3120 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
3123
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003124 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003128 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129
chaviw82357092020-01-28 13:13:06 -08003130 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3133 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003134 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003135 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3136 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003137 // Don't apply window scale here since we don't want scale to affect raw
3138 // coordinates. The scale will be sent back to the client and applied
3139 // later when requesting relative coordinates.
3140 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3141 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 }
3143 usingCoords = scaledCoords;
3144 }
3145 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146 // We don't want the dispatch target to know.
3147 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003148 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 scaledCoords[i].clear();
3150 }
3151 usingCoords = scaledCoords;
3152 }
3153 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003154
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003155 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156
3157 // Publish the motion event.
3158 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003159 .publishMotionEvent(dispatchEntry->seq,
3160 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 motionEntry.deviceId, motionEntry.source,
3162 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003163 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003166 motionEntry.edgeFlags, motionEntry.metaState,
3167 motionEntry.buttonState,
3168 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003169 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003170 motionEntry.xPrecision, motionEntry.yPrecision,
3171 motionEntry.xCursorPosition,
3172 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003173 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003174 dispatchEntry->displaySize.x,
3175 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003176 motionEntry.downTime, motionEntry.eventTime,
3177 motionEntry.pointerCount,
3178 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 break;
3180 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003181
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003182 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003183 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003184 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003185 focusEntry.id,
3186 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003187 mInTouchMode);
3188 break;
3189 }
3190
Prabir Pradhan99987712020-11-10 18:43:05 -08003191 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3192 const auto& captureEntry =
3193 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3194 status = connection->inputPublisher
3195 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3196 captureEntry.pointerCaptureEnabled);
3197 break;
3198 }
3199
arthurhungb89ccb02020-12-30 16:19:01 +08003200 case EventEntry::Type::DRAG: {
3201 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3202 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3203 dragEntry.id, dragEntry.x,
3204 dragEntry.y,
3205 dragEntry.isExiting);
3206 break;
3207 }
3208
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003209 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003210 case EventEntry::Type::DEVICE_RESET:
3211 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003212 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003213 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003214 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 }
3217
3218 // Check the result.
3219 if (status) {
3220 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003221 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 "This is unexpected because the wait queue is empty, so the pipe "
3224 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003225 "event to it, status=%s(%d)",
3226 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3227 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3229 } else {
3230 // Pipe is full and we are waiting for the app to finish process some events
3231 // before sending more events to it.
3232#if DEBUG_DISPATCH_CYCLE
3233 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 "waiting for the application to catch up",
3235 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 }
3238 } else {
3239 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003240 "status=%s(%d)",
3241 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3242 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3244 }
3245 return;
3246 }
3247
3248 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003249 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3250 connection->outboundQueue.end(),
3251 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003252 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003253 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003254 if (connection->responsive) {
3255 mAnrTracker.insert(dispatchEntry->timeoutTime,
3256 connection->inputChannel->getConnectionToken());
3257 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003258 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 }
3260}
3261
chaviw09c8d2d2020-08-24 15:48:26 -07003262std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3263 size_t size;
3264 switch (event.type) {
3265 case VerifiedInputEvent::Type::KEY: {
3266 size = sizeof(VerifiedKeyEvent);
3267 break;
3268 }
3269 case VerifiedInputEvent::Type::MOTION: {
3270 size = sizeof(VerifiedMotionEvent);
3271 break;
3272 }
3273 }
3274 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3275 return mHmacKeyManager.sign(start, size);
3276}
3277
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003278const std::array<uint8_t, 32> InputDispatcher::getSignature(
3279 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3280 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3281 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3282 // Only sign events up and down events as the purely move events
3283 // are tied to their up/down counterparts so signing would be redundant.
3284 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3285 verifiedEvent.actionMasked = actionMasked;
3286 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003287 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003288 }
3289 return INVALID_HMAC;
3290}
3291
3292const std::array<uint8_t, 32> InputDispatcher::getSignature(
3293 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3294 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3295 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3296 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003297 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003298}
3299
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003302 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303#if DEBUG_DISPATCH_CYCLE
3304 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306#endif
3307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 if (connection->status == Connection::STATUS_BROKEN ||
3309 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 return;
3311 }
3312
3313 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003314 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315}
3316
3317void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 const sp<Connection>& connection,
3319 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320#if DEBUG_DISPATCH_CYCLE
3321 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323#endif
3324
3325 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003326 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003327 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003328 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003329 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
3331 // The connection appears to be unrecoverably broken.
3332 // Ignore already broken or zombie connections.
3333 if (connection->status == Connection::STATUS_NORMAL) {
3334 connection->status = Connection::STATUS_BROKEN;
3335
3336 if (notify) {
3337 // Notify other system components.
3338 onDispatchCycleBrokenLocked(currentTime, connection);
3339 }
3340 }
3341}
3342
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003343void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3344 while (!queue.empty()) {
3345 DispatchEntry* dispatchEntry = queue.front();
3346 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003347 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 }
3349}
3350
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003351void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003353 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 }
3355 delete dispatchEntry;
3356}
3357
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003358int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3359 std::scoped_lock _l(mLock);
3360 sp<Connection> connection = getConnectionLocked(connectionToken);
3361 if (connection == nullptr) {
3362 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3363 connectionToken.get(), events);
3364 return 0; // remove the callback
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003367 bool notify;
3368 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3369 if (!(events & ALOOPER_EVENT_INPUT)) {
3370 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3371 "events=0x%x",
3372 connection->getInputChannelName().c_str(), events);
3373 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
3375
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003376 nsecs_t currentTime = now();
3377 bool gotOne = false;
3378 status_t status = OK;
3379 for (;;) {
3380 Result<InputPublisher::ConsumerResponse> result =
3381 connection->inputPublisher.receiveConsumerResponse();
3382 if (!result.ok()) {
3383 status = result.error().code();
3384 break;
3385 }
3386
3387 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3388 const InputPublisher::Finished& finish =
3389 std::get<InputPublisher::Finished>(*result);
3390 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3391 finish.consumeTime);
3392 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003393 if (shouldReportMetricsForConnection(*connection)) {
3394 const InputPublisher::Timeline& timeline =
3395 std::get<InputPublisher::Timeline>(*result);
3396 mLatencyTracker
3397 .trackGraphicsLatency(timeline.inputEventId,
3398 connection->inputChannel->getConnectionToken(),
3399 std::move(timeline.graphicsTimeline));
3400 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003401 }
3402 gotOne = true;
3403 }
3404 if (gotOne) {
3405 runCommandsLockedInterruptible();
3406 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 return 1;
3408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
3410
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003411 notify = status != DEAD_OBJECT || !connection->monitor;
3412 if (notify) {
3413 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3414 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3415 status);
3416 }
3417 } else {
3418 // Monitor channels are never explicitly unregistered.
3419 // We do it automatically when the remote endpoint is closed so don't warn about them.
3420 const bool stillHaveWindowHandle =
3421 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3422 notify = !connection->monitor && stillHaveWindowHandle;
3423 if (notify) {
3424 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3425 connection->getInputChannelName().c_str(), events);
3426 }
3427 }
3428
3429 // Remove the channel.
3430 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3431 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432}
3433
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003436 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003437 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 }
3439}
3440
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003442 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003443 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3444 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3445}
3446
3447void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3448 const CancelationOptions& options,
3449 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3450 for (const auto& it : monitorsByDisplay) {
3451 const std::vector<Monitor>& monitors = it.second;
3452 for (const Monitor& monitor : monitors) {
3453 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003454 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003455 }
3456}
3457
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003459 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003460 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003461 if (connection == nullptr) {
3462 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003464
3465 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466}
3467
3468void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3469 const sp<Connection>& connection, const CancelationOptions& options) {
3470 if (connection->status == Connection::STATUS_BROKEN) {
3471 return;
3472 }
3473
3474 nsecs_t currentTime = now();
3475
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003476 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003477 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003479 if (cancelationEvents.empty()) {
3480 return;
3481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003483 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3484 "with reality: %s, mode=%d.",
3485 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3486 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003488
3489 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003490 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003491 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3492 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003493 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003494 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003495 target.globalScaleFactor = windowInfo->globalScaleFactor;
3496 }
3497 target.inputChannel = connection->inputChannel;
3498 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3499
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003500 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003501 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003502 switch (cancelationEventEntry->type) {
3503 case EventEntry::Type::KEY: {
3504 logOutboundKeyDetails("cancel - ",
3505 static_cast<const KeyEntry&>(*cancelationEventEntry));
3506 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003508 case EventEntry::Type::MOTION: {
3509 logOutboundMotionDetails("cancel - ",
3510 static_cast<const MotionEntry&>(*cancelationEventEntry));
3511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003513 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3515 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003516 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003517 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003518 break;
3519 }
3520 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003521 case EventEntry::Type::DEVICE_RESET:
3522 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003523 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003524 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003525 break;
3526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003529 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3530 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003532
3533 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534}
3535
Svet Ganov5d3bc372020-01-26 23:11:07 -08003536void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3537 const sp<Connection>& connection) {
3538 if (connection->status == Connection::STATUS_BROKEN) {
3539 return;
3540 }
3541
3542 nsecs_t currentTime = now();
3543
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003544 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003545 connection->inputState.synthesizePointerDownEvents(currentTime);
3546
3547 if (downEvents.empty()) {
3548 return;
3549 }
3550
3551#if DEBUG_OUTBOUND_EVENT_DETAILS
3552 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3553 connection->getInputChannelName().c_str(), downEvents.size());
3554#endif
3555
3556 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003557 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003558 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3559 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003560 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003561 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003562 target.globalScaleFactor = windowInfo->globalScaleFactor;
3563 }
3564 target.inputChannel = connection->inputChannel;
3565 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003567 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003568 switch (downEventEntry->type) {
3569 case EventEntry::Type::MOTION: {
3570 logOutboundMotionDetails("down - ",
3571 static_cast<const MotionEntry&>(*downEventEntry));
3572 break;
3573 }
3574
3575 case EventEntry::Type::KEY:
3576 case EventEntry::Type::FOCUS:
3577 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003578 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003579 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003580 case EventEntry::Type::SENSOR:
3581 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003583 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003584 break;
3585 }
3586 }
3587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003588 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3589 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003590 }
3591
3592 startDispatchCycleLocked(currentTime, connection);
3593}
3594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3596 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 ALOG_ASSERT(pointerIds.value != 0);
3598
3599 uint32_t splitPointerIndexMap[MAX_POINTERS];
3600 PointerProperties splitPointerProperties[MAX_POINTERS];
3601 PointerCoords splitPointerCoords[MAX_POINTERS];
3602
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003603 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 uint32_t splitPointerCount = 0;
3605
3606 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003609 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 uint32_t pointerId = uint32_t(pointerProperties.id);
3611 if (pointerIds.hasBit(pointerId)) {
3612 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3613 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3614 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003615 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 splitPointerCount += 1;
3617 }
3618 }
3619
3620 if (splitPointerCount != pointerIds.count()) {
3621 // This is bad. We are missing some of the pointers that we expected to deliver.
3622 // Most likely this indicates that we received an ACTION_MOVE events that has
3623 // different pointer ids than we expected based on the previous ACTION_DOWN
3624 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3625 // in this way.
3626 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 "we expected there to be %d pointers. This probably means we received "
3628 "a broken sequence of pointer ids from the input device.",
3629 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003630 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 }
3632
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003633 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003635 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3636 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3638 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003639 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 uint32_t pointerId = uint32_t(pointerProperties.id);
3641 if (pointerIds.hasBit(pointerId)) {
3642 if (pointerIds.count() == 1) {
3643 // The first/last pointer went down/up.
3644 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003645 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003646 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3647 ? AMOTION_EVENT_ACTION_CANCEL
3648 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 } else {
3650 // A secondary pointer went down/up.
3651 uint32_t splitPointerIndex = 0;
3652 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3653 splitPointerIndex += 1;
3654 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003655 action = maskedAction |
3656 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658 } else {
3659 // An unrelated pointer changed.
3660 action = AMOTION_EVENT_ACTION_MOVE;
3661 }
3662 }
3663
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003664 int32_t newId = mIdGenerator.nextId();
3665 if (ATRACE_ENABLED()) {
3666 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3667 ") to MotionEvent(id=0x%" PRIx32 ").",
3668 originalMotionEntry.id, newId);
3669 ATRACE_NAME(message.c_str());
3670 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003671 std::unique_ptr<MotionEntry> splitMotionEntry =
3672 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3673 originalMotionEntry.deviceId, originalMotionEntry.source,
3674 originalMotionEntry.displayId,
3675 originalMotionEntry.policyFlags, action,
3676 originalMotionEntry.actionButton,
3677 originalMotionEntry.flags, originalMotionEntry.metaState,
3678 originalMotionEntry.buttonState,
3679 originalMotionEntry.classification,
3680 originalMotionEntry.edgeFlags,
3681 originalMotionEntry.xPrecision,
3682 originalMotionEntry.yPrecision,
3683 originalMotionEntry.xCursorPosition,
3684 originalMotionEntry.yCursorPosition,
3685 originalMotionEntry.downTime, splitPointerCount,
3686 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003688 if (originalMotionEntry.injectionState) {
3689 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 splitMotionEntry->injectionState->refCount += 1;
3691 }
3692
3693 return splitMotionEntry;
3694}
3695
3696void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3697#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003698 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699#endif
3700
3701 bool needWake;
3702 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003703 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003705 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3706 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3707 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 } // release lock
3709
3710 if (needWake) {
3711 mLooper->wake();
3712 }
3713}
3714
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003715/**
3716 * If one of the meta shortcuts is detected, process them here:
3717 * Meta + Backspace -> generate BACK
3718 * Meta + Enter -> generate HOME
3719 * This will potentially overwrite keyCode and metaState.
3720 */
3721void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003723 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3724 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3725 if (keyCode == AKEYCODE_DEL) {
3726 newKeyCode = AKEYCODE_BACK;
3727 } else if (keyCode == AKEYCODE_ENTER) {
3728 newKeyCode = AKEYCODE_HOME;
3729 }
3730 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003731 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003732 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003733 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003734 keyCode = newKeyCode;
3735 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3736 }
3737 } else if (action == AKEY_EVENT_ACTION_UP) {
3738 // In order to maintain a consistent stream of up and down events, check to see if the key
3739 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3740 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003741 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003742 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003743 auto replacementIt = mReplacedKeys.find(replacement);
3744 if (replacementIt != mReplacedKeys.end()) {
3745 keyCode = replacementIt->second;
3746 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003747 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3748 }
3749 }
3750}
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3753#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3755 "policyFlags=0x%x, action=0x%x, "
3756 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3757 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3758 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3759 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760#endif
3761 if (!validateKeyEvent(args->action)) {
3762 return;
3763 }
3764
3765 uint32_t policyFlags = args->policyFlags;
3766 int32_t flags = args->flags;
3767 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003768 // InputDispatcher tracks and generates key repeats on behalf of
3769 // whatever notifies it, so repeatCount should always be set to 0
3770 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3772 policyFlags |= POLICY_FLAG_VIRTUAL;
3773 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 if (policyFlags & POLICY_FLAG_FUNCTION) {
3776 metaState |= AMETA_FUNCTION_ON;
3777 }
3778
3779 policyFlags |= POLICY_FLAG_TRUSTED;
3780
Michael Wright78f24442014-08-06 15:55:28 -07003781 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003782 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003783
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003785 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003786 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3787 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788
Michael Wright2b3c3302018-03-02 17:19:13 +00003789 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003791 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3792 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 bool needWake;
3797 { // acquire lock
3798 mLock.lock();
3799
3800 if (shouldSendKeyToInputFilterLocked(args)) {
3801 mLock.unlock();
3802
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003803 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3805 return; // event was consumed by the filter
3806 }
3807
3808 mLock.lock();
3809 }
3810
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003811 std::unique_ptr<KeyEntry> newEntry =
3812 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3813 args->displayId, policyFlags, args->action, flags,
3814 keyCode, args->scanCode, metaState, repeatCount,
3815 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003817 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 mLock.unlock();
3819 } // release lock
3820
3821 if (needWake) {
3822 mLooper->wake();
3823 }
3824}
3825
3826bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3827 return mInputFilterEnabled;
3828}
3829
3830void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3831#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003832 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3833 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003834 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3835 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003836 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003837 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3838 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3839 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3840 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 for (uint32_t i = 0; i < args->pointerCount; i++) {
3842 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003843 "x=%f, y=%f, pressure=%f, size=%f, "
3844 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3845 "orientation=%f",
3846 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3847 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3848 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3849 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3850 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3851 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3852 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3853 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3854 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3855 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 }
3857#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003858 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3859 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 return;
3861 }
3862
3863 uint32_t policyFlags = args->policyFlags;
3864 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003865
3866 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003867 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003868 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3869 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003870 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872
3873 bool needWake;
3874 { // acquire lock
3875 mLock.lock();
3876
3877 if (shouldSendMotionToInputFilterLocked(args)) {
3878 mLock.unlock();
3879
3880 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003881 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003882 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3883 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003884 args->metaState, args->buttonState, args->classification, transform,
3885 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003886 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3887 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3888 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889
3890 policyFlags |= POLICY_FLAG_FILTERED;
3891 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3892 return; // event was consumed by the filter
3893 }
3894
3895 mLock.lock();
3896 }
3897
3898 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003899 std::unique_ptr<MotionEntry> newEntry =
3900 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3901 args->source, args->displayId, policyFlags,
3902 args->action, args->actionButton, args->flags,
3903 args->metaState, args->buttonState,
3904 args->classification, args->edgeFlags,
3905 args->xPrecision, args->yPrecision,
3906 args->xCursorPosition, args->yCursorPosition,
3907 args->downTime, args->pointerCount,
3908 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003910 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 mLock.unlock();
3912 } // release lock
3913
3914 if (needWake) {
3915 mLooper->wake();
3916 }
3917}
3918
Chris Yef59a2f42020-10-16 12:55:26 -07003919void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3920#if DEBUG_INBOUND_EVENT_DETAILS
3921 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3922 " sensorType=%s",
3923 args->id, args->eventTime, args->deviceId, args->source,
3924 NamedEnum::string(args->sensorType).c_str());
3925#endif
3926
3927 bool needWake;
3928 { // acquire lock
3929 mLock.lock();
3930
3931 // Just enqueue a new sensor event.
3932 std::unique_ptr<SensorEntry> newEntry =
3933 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3934 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3935 args->sensorType, args->accuracy,
3936 args->accuracyChanged, args->values);
3937
3938 needWake = enqueueInboundEventLocked(std::move(newEntry));
3939 mLock.unlock();
3940 } // release lock
3941
3942 if (needWake) {
3943 mLooper->wake();
3944 }
3945}
3946
Chris Yefb552902021-02-03 17:18:37 -08003947void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3948#if DEBUG_INBOUND_EVENT_DETAILS
3949 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3950 args->deviceId, args->isOn);
3951#endif
3952 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3953}
3954
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003956 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957}
3958
3959void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3960#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003961 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 "switchMask=0x%08x",
3963 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964#endif
3965
3966 uint32_t policyFlags = args->policyFlags;
3967 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003968 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969}
3970
3971void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3972#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3974 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975#endif
3976
3977 bool needWake;
3978 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003979 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003981 std::unique_ptr<DeviceResetEntry> newEntry =
3982 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3983 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 } // release lock
3985
3986 if (needWake) {
3987 mLooper->wake();
3988 }
3989}
3990
Prabir Pradhan7e186182020-11-10 13:56:45 -08003991void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3992#if DEBUG_INBOUND_EVENT_DETAILS
3993 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3994 args->enabled ? "true" : "false");
3995#endif
3996
Prabir Pradhan99987712020-11-10 18:43:05 -08003997 bool needWake;
3998 { // acquire lock
3999 std::scoped_lock _l(mLock);
4000 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
4001 args->enabled);
4002 needWake = enqueueInboundEventLocked(std::move(entry));
4003 } // release lock
4004
4005 if (needWake) {
4006 mLooper->wake();
4007 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004008}
4009
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004010InputEventInjectionResult InputDispatcher::injectInputEvent(
4011 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4012 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013#if DEBUG_INBOUND_EVENT_DETAILS
4014 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004015 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4016 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004018 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
4020 policyFlags |= POLICY_FLAG_INJECTED;
4021 if (hasInjectionPermission(injectorPid, injectorUid)) {
4022 policyFlags |= POLICY_FLAG_TRUSTED;
4023 }
4024
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004025 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004026 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4027 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4028 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4029 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4030 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004031 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004032 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004033 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004034 }
4035
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004039 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4040 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004041 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004045 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004046 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4047 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4048 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004049 int32_t keyCode = incomingKey.getKeyCode();
4050 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004051 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004053 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004054 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004055 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4056 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4057 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4060 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062
4063 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4064 android::base::Timer t;
4065 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4066 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4067 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4068 std::to_string(t.duration().count()).c_str());
4069 }
4070 }
4071
4072 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004073 std::unique_ptr<KeyEntry> injectedEntry =
4074 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004075 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004076 incomingKey.getDisplayId(), policyFlags, action,
4077 flags, keyCode, incomingKey.getScanCode(), metaState,
4078 incomingKey.getRepeatCount(),
4079 incomingKey.getDownTime());
4080 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 }
4083
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004084 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004085 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4086 int32_t action = motionEvent.getAction();
4087 size_t pointerCount = motionEvent.getPointerCount();
4088 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4089 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004090 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004091 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004093 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 }
4095
4096 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004097 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004098 android::base::Timer t;
4099 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4100 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4101 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4102 std::to_string(t.duration().count()).c_str());
4103 }
4104 }
4105
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004106 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4107 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4108 }
4109
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004111 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4112 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004113 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004114 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4115 resolvedDeviceId, motionEvent.getSource(),
4116 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004117 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004118 motionEvent.getButtonState(),
4119 motionEvent.getClassification(),
4120 motionEvent.getEdgeFlags(),
4121 motionEvent.getXPrecision(),
4122 motionEvent.getYPrecision(),
4123 motionEvent.getRawXCursorPosition(),
4124 motionEvent.getRawYCursorPosition(),
4125 motionEvent.getDownTime(), uint32_t(pointerCount),
4126 pointerProperties, samplePointerCoords,
4127 motionEvent.getXOffset(),
4128 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004129 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 sampleEventTimes += 1;
4132 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004133 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004134 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4135 resolvedDeviceId, motionEvent.getSource(),
4136 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004137 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004138 motionEvent.getMetaState(),
4139 motionEvent.getButtonState(),
4140 motionEvent.getClassification(),
4141 motionEvent.getEdgeFlags(),
4142 motionEvent.getXPrecision(),
4143 motionEvent.getYPrecision(),
4144 motionEvent.getRawXCursorPosition(),
4145 motionEvent.getRawYCursorPosition(),
4146 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004147 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004148 samplePointerCoords, motionEvent.getXOffset(),
4149 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004150 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 }
4152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004156 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004157 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159
4160 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004161 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 injectionState->injectionIsAsync = true;
4163 }
4164
4165 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004166 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
4168 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004169 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004170 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004171 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
4173
4174 mLock.unlock();
4175
4176 if (needWake) {
4177 mLooper->wake();
4178 }
4179
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004180 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004182 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004184 if (syncMode == InputEventInjectionSync::NONE) {
4185 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 } else {
4187 for (;;) {
4188 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004189 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 }
4192
4193 nsecs_t remainingTimeout = endTime - now();
4194 if (remainingTimeout <= 0) {
4195#if DEBUG_INJECTION
4196 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004199 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 break;
4201 }
4202
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004203 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 }
4205
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004206 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4207 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 while (injectionState->pendingForegroundDispatches != 0) {
4209#if DEBUG_INJECTION
4210 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212#endif
4213 nsecs_t remainingTimeout = endTime - now();
4214 if (remainingTimeout <= 0) {
4215#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4217 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 break;
4221 }
4222
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004223 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 }
4225 }
4226 }
4227
4228 injectionState->release();
4229 } // release lock
4230
4231#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004232 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234#endif
4235
4236 return injectionResult;
4237}
4238
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004239std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004240 std::array<uint8_t, 32> calculatedHmac;
4241 std::unique_ptr<VerifiedInputEvent> result;
4242 switch (event.getType()) {
4243 case AINPUT_EVENT_TYPE_KEY: {
4244 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4245 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4246 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004247 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004248 break;
4249 }
4250 case AINPUT_EVENT_TYPE_MOTION: {
4251 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4252 VerifiedMotionEvent verifiedMotionEvent =
4253 verifiedMotionEventFromMotionEvent(motionEvent);
4254 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004255 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004256 break;
4257 }
4258 default: {
4259 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4260 return nullptr;
4261 }
4262 }
4263 if (calculatedHmac == INVALID_HMAC) {
4264 return nullptr;
4265 }
4266 if (calculatedHmac != event.getHmac()) {
4267 return nullptr;
4268 }
4269 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004270}
4271
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 return injectorUid == 0 ||
4274 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275}
4276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004277void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004278 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 if (injectionState) {
4281#if DEBUG_INJECTION
4282 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 "injectorPid=%d, injectorUid=%d",
4284 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285#endif
4286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 // Log the outcome since the injector did not wait for the injection result.
4289 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004290 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 ALOGV("Asynchronous input event injection succeeded.");
4292 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004293 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 ALOGW("Asynchronous input event injection failed.");
4295 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004296 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 ALOGW("Asynchronous input event injection permission denied.");
4298 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004299 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 ALOGW("Asynchronous input event injection timed out.");
4301 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004302 case InputEventInjectionResult::PENDING:
4303 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306 }
4307
4308 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004309 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311}
4312
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4314 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 if (injectionState) {
4316 injectionState->pendingForegroundDispatches += 1;
4317 }
4318}
4319
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004320void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4321 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 if (injectionState) {
4323 injectionState->pendingForegroundDispatches -= 1;
4324
4325 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004326 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328 }
4329}
4330
chaviw3277faf2021-05-19 16:45:23 -05004331const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004332 int32_t displayId) const {
chaviw3277faf2021-05-19 16:45:23 -05004333 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004334 auto it = mWindowHandlesByDisplay.find(displayId);
4335 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004336}
4337
chaviw3277faf2021-05-19 16:45:23 -05004338sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004339 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004340 if (windowHandleToken == nullptr) {
4341 return nullptr;
4342 }
4343
Arthur Hungb92218b2018-08-14 12:00:21 +08004344 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004345 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4346 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004347 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004348 return windowHandle;
4349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
4351 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004352 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353}
4354
chaviw3277faf2021-05-19 16:45:23 -05004355sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4356 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004357 if (windowHandleToken == nullptr) {
4358 return nullptr;
4359 }
4360
chaviw3277faf2021-05-19 16:45:23 -05004361 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004362 if (windowHandle->getToken() == windowHandleToken) {
4363 return windowHandle;
4364 }
4365 }
4366 return nullptr;
4367}
4368
chaviw3277faf2021-05-19 16:45:23 -05004369sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4370 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004371 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004372 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4373 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004374 if (handle->getId() == windowHandle->getId() &&
4375 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004376 if (windowHandle->getInfo()->displayId != it.first) {
4377 ALOGE("Found window %s in display %" PRId32
4378 ", but it should belong to display %" PRId32,
4379 windowHandle->getName().c_str(), it.first,
4380 windowHandle->getInfo()->displayId);
4381 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004382 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004386 return nullptr;
4387}
4388
chaviw3277faf2021-05-19 16:45:23 -05004389sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004390 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4391 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392}
4393
chaviw3277faf2021-05-19 16:45:23 -05004394bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004395 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4396 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004397 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004398 if (connection != nullptr && noInputChannel) {
4399 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4400 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4401 return false;
4402 }
4403
4404 if (connection == nullptr) {
4405 if (!noInputChannel) {
4406 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4407 }
4408 return false;
4409 }
4410 if (!connection->responsive) {
4411 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4412 return false;
4413 }
4414 return true;
4415}
4416
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004417std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4418 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004419 auto connectionIt = mConnectionsByToken.find(token);
4420 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004421 return nullptr;
4422 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004423 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004424}
4425
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004426void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw3277faf2021-05-19 16:45:23 -05004427 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4428 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004429 // Remove all handles on a display if there are no windows left.
4430 mWindowHandlesByDisplay.erase(displayId);
4431 return;
4432 }
4433
4434 // Since we compare the pointer of input window handles across window updates, we need
4435 // to make sure the handle object for the same window stays unchanged across updates.
chaviw3277faf2021-05-19 16:45:23 -05004436 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4437 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4438 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004439 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004440 }
4441
chaviw3277faf2021-05-19 16:45:23 -05004442 std::vector<sp<WindowInfoHandle>> newHandles;
4443 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004444 if (!handle->updateInfo()) {
4445 // handle no longer valid
4446 continue;
4447 }
4448
chaviw3277faf2021-05-19 16:45:23 -05004449 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004450 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4451 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4452 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004453 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4454 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4455 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004456 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004457 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004458 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004459 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004460 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004461 }
4462
4463 if (info->displayId != displayId) {
4464 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4465 handle->getName().c_str(), displayId, info->displayId);
4466 continue;
4467 }
4468
Robert Carredd13602020-04-13 17:24:34 -07004469 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4470 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw3277faf2021-05-19 16:45:23 -05004471 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004472 oldHandle->updateFrom(handle);
4473 newHandles.push_back(oldHandle);
4474 } else {
4475 newHandles.push_back(handle);
4476 }
4477 }
4478
4479 // Insert or replace
4480 mWindowHandlesByDisplay[displayId] = newHandles;
4481}
4482
Arthur Hung72d8dc32020-03-28 00:48:39 +00004483void InputDispatcher::setInputWindows(
chaviw3277faf2021-05-19 16:45:23 -05004484 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004485 { // acquire lock
4486 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004487 for (const auto& [displayId, handles] : handlesPerDisplay) {
4488 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004489 }
4490 }
4491 // Wake up poll loop since it may need to make new input dispatching choices.
4492 mLooper->wake();
4493}
4494
Arthur Hungb92218b2018-08-14 12:00:21 +08004495/**
4496 * Called from InputManagerService, update window handle list by displayId that can receive input.
4497 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4498 * If set an empty list, remove all handles from the specific display.
4499 * For focused handle, check if need to change and send a cancel event to previous one.
4500 * For removed handle, check if need to send a cancel event if already in touch.
4501 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004502void InputDispatcher::setInputWindowsLocked(
chaviw3277faf2021-05-19 16:45:23 -05004503 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004504 if (DEBUG_FOCUS) {
4505 std::string windowList;
chaviw3277faf2021-05-19 16:45:23 -05004506 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004507 windowList += iwh->getName() + " ";
4508 }
4509 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004512 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw3277faf2021-05-19 16:45:23 -05004513 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004514 const bool noInputWindow =
chaviw3277faf2021-05-19 16:45:23 -05004515 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004516 if (noInputWindow && window->getToken() != nullptr) {
4517 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4518 window->getName().c_str());
4519 window->releaseChannel();
4520 }
4521 }
4522
Arthur Hung72d8dc32020-03-28 00:48:39 +00004523 // Copy old handles for release if they are no longer present.
chaviw3277faf2021-05-19 16:45:23 -05004524 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004526 // Save the old windows' orientation by ID before it gets updated.
4527 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw3277faf2021-05-19 16:45:23 -05004528 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004529 oldWindowOrientations.emplace(handle->getId(),
4530 handle->getInfo()->transform.getOrientation());
4531 }
4532
chaviw3277faf2021-05-19 16:45:23 -05004533 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004534
chaviw3277faf2021-05-19 16:45:23 -05004535 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004536 if (mLastHoverWindowHandle &&
4537 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4538 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004539 mLastHoverWindowHandle = nullptr;
4540 }
4541
Vishnu Nairc519ff72021-01-21 08:23:08 -08004542 std::optional<FocusResolver::FocusChanges> changes =
4543 mFocusResolver.setInputWindows(displayId, windowHandles);
4544 if (changes) {
4545 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004548 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4549 mTouchStatesByDisplay.find(displayId);
4550 if (stateIt != mTouchStatesByDisplay.end()) {
4551 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004552 for (size_t i = 0; i < state.windows.size();) {
4553 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004554 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004555 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004556 ALOGD("Touched window was removed: %s in display %" PRId32,
4557 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004558 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004559 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004560 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4561 if (touchedInputChannel != nullptr) {
4562 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4563 "touched window was removed");
4564 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004566 state.windows.erase(state.windows.begin() + i);
4567 } else {
4568 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 }
4570 }
arthurhungb89ccb02020-12-30 16:19:01 +08004571
arthurhung6d4bed92021-03-17 11:59:33 +08004572 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004573 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004574 if (mDragState &&
4575 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004576 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004577 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004578 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004579 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004580
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004581 if (isPerWindowInputRotationEnabled()) {
4582 // Determine if the orientation of any of the input windows have changed, and cancel all
4583 // pointer events if necessary.
chaviw3277faf2021-05-19 16:45:23 -05004584 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4585 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004586 if (newWindowHandle != nullptr &&
4587 newWindowHandle->getInfo()->transform.getOrientation() !=
4588 oldWindowOrientations[oldWindowHandle->getId()]) {
4589 std::shared_ptr<InputChannel> inputChannel =
4590 getInputChannelLocked(newWindowHandle->getToken());
4591 if (inputChannel != nullptr) {
4592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4593 "touched window's orientation changed");
4594 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4595 }
4596 }
4597 }
4598 }
4599
Arthur Hung72d8dc32020-03-28 00:48:39 +00004600 // Release information for windows that are no longer present.
4601 // This ensures that unused input channels are released promptly.
4602 // Otherwise, they might stick around until the window handle is destroyed
4603 // which might not happen until the next GC.
chaviw3277faf2021-05-19 16:45:23 -05004604 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004605 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606 if (DEBUG_FOCUS) {
4607 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004608 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004609 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004610 // To avoid making too many calls into the compat framework, only
4611 // check for window flags when windows are going away.
4612 // TODO(b/157929241) : delete this. This is only needed temporarily
4613 // in order to gather some data about the flag usage
chaviw3277faf2021-05-19 16:45:23 -05004614 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004615 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4616 oldWindowHandle->getName().c_str());
4617 if (mCompatService != nullptr) {
4618 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4619 oldWindowHandle->getInfo()->ownerUid);
4620 }
4621 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004622 }
chaviw291d88a2019-02-14 10:33:58 -08004623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624}
4625
4626void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004627 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004628 if (DEBUG_FOCUS) {
4629 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4630 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4631 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004632 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004633 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004634 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 } // release lock
4636
4637 // Wake up poll loop since it may need to make new input dispatching choices.
4638 mLooper->wake();
4639}
4640
Vishnu Nair599f1412021-06-21 10:39:58 -07004641void InputDispatcher::setFocusedApplicationLocked(
4642 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4643 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4644 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4645
4646 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4647 return; // This application is already focused. No need to wake up or change anything.
4648 }
4649
4650 // Set the new application handle.
4651 if (inputApplicationHandle != nullptr) {
4652 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4653 } else {
4654 mFocusedApplicationHandlesByDisplay.erase(displayId);
4655 }
4656
4657 // No matter what the old focused application was, stop waiting on it because it is
4658 // no longer focused.
4659 resetNoFocusedWindowTimeoutLocked();
4660}
4661
Tiger Huang721e26f2018-07-24 22:26:19 +08004662/**
4663 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4664 * the display not specified.
4665 *
4666 * We track any unreleased events for each window. If a window loses the ability to receive the
4667 * released event, we will send a cancel event to it. So when the focused display is changed, we
4668 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4669 * display. The display-specified events won't be affected.
4670 */
4671void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004672 if (DEBUG_FOCUS) {
4673 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4674 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004675 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004676 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004677
4678 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004679 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004680 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004681 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004682 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004683 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004684 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 CancelationOptions
4686 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4687 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004688 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004689 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4690 }
4691 }
4692 mFocusedDisplayId = displayId;
4693
Chris Ye3c2d6f52020-08-09 10:39:48 -07004694 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004695 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004696 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004697
Vishnu Nairad321cd2020-08-20 16:40:21 -07004698 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004699 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004700 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004701 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004702 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004703 }
4704 }
4705 }
4706
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004707 if (DEBUG_FOCUS) {
4708 logDispatchStateLocked();
4709 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004710 } // release lock
4711
4712 // Wake up poll loop since it may need to make new input dispatching choices.
4713 mLooper->wake();
4714}
4715
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004717 if (DEBUG_FOCUS) {
4718 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720
4721 bool changed;
4722 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004723 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
4725 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4726 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729
4730 if (mDispatchEnabled && !enabled) {
4731 resetAndDropEverythingLocked("dispatcher is being disabled");
4732 }
4733
4734 mDispatchEnabled = enabled;
4735 mDispatchFrozen = frozen;
4736 changed = true;
4737 } else {
4738 changed = false;
4739 }
4740
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004741 if (DEBUG_FOCUS) {
4742 logDispatchStateLocked();
4743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 } // release lock
4745
4746 if (changed) {
4747 // Wake up poll loop since it may need to make new input dispatching choices.
4748 mLooper->wake();
4749 }
4750}
4751
4752void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004753 if (DEBUG_FOCUS) {
4754 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756
4757 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004758 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759
4760 if (mInputFilterEnabled == enabled) {
4761 return;
4762 }
4763
4764 mInputFilterEnabled = enabled;
4765 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4766 } // release lock
4767
4768 // Wake up poll loop since there might be work to do to drop everything.
4769 mLooper->wake();
4770}
4771
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004772void InputDispatcher::setInTouchMode(bool inTouchMode) {
4773 std::scoped_lock lock(mLock);
4774 mInTouchMode = inTouchMode;
4775}
4776
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004777void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4778 if (opacity < 0 || opacity > 1) {
4779 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4780 return;
4781 }
4782
4783 std::scoped_lock lock(mLock);
4784 mMaximumObscuringOpacityForTouch = opacity;
4785}
4786
4787void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4788 std::scoped_lock lock(mLock);
4789 mBlockUntrustedTouchesMode = mode;
4790}
4791
arthurhungb89ccb02020-12-30 16:19:01 +08004792bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4793 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004794 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004795 if (DEBUG_FOCUS) {
4796 ALOGD("Trivial transfer to same window.");
4797 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004798 return true;
4799 }
4800
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004802 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
chaviw3277faf2021-05-19 16:45:23 -05004804 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4805 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004806 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004807 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 return false;
4809 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004810 if (DEBUG_FOCUS) {
4811 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4812 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004815 if (DEBUG_FOCUS) {
4816 ALOGD("Cannot transfer focus because windows are on different displays.");
4817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 return false;
4819 }
4820
4821 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004822 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4823 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004824 for (size_t i = 0; i < state.windows.size(); i++) {
4825 const TouchedWindow& touchedWindow = state.windows[i];
4826 if (touchedWindow.windowHandle == fromWindowHandle) {
4827 int32_t oldTargetFlags = touchedWindow.targetFlags;
4828 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004830 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 int32_t newTargetFlags = oldTargetFlags &
4833 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4834 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004835 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836
arthurhungb89ccb02020-12-30 16:19:01 +08004837 // Store the dragging window.
4838 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004839 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004840 }
4841
Jeff Brownf086ddb2014-02-11 14:28:48 -08004842 found = true;
4843 goto Found;
4844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004850 if (DEBUG_FOCUS) {
4851 ALOGD("Focus transfer failed because from window did not have focus.");
4852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 return false;
4854 }
4855
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004856 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4857 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004858 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004859 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860 CancelationOptions
4861 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4862 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004864 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004867 if (DEBUG_FOCUS) {
4868 logDispatchStateLocked();
4869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 } // release lock
4871
4872 // Wake up poll loop since it may need to make new input dispatching choices.
4873 mLooper->wake();
4874 return true;
4875}
4876
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004877// Binder call
4878bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4879 sp<IBinder> fromToken;
4880 { // acquire lock
4881 std::scoped_lock _l(mLock);
4882
chaviw3277faf2021-05-19 16:45:23 -05004883 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004884 if (toWindowHandle == nullptr) {
4885 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4886 return false;
4887 }
4888
4889 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4890
4891 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4892 if (touchStateIt == mTouchStatesByDisplay.end()) {
4893 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4894 displayId);
4895 return false;
4896 }
4897
4898 TouchState& state = touchStateIt->second;
4899 if (state.windows.size() != 1) {
4900 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4901 state.windows.size());
4902 return false;
4903 }
4904 const TouchedWindow& touchedWindow = state.windows[0];
4905 fromToken = touchedWindow.windowHandle->getToken();
4906 } // release lock
4907
4908 return transferTouchFocus(fromToken, destChannelToken);
4909}
4910
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004912 if (DEBUG_FOCUS) {
4913 ALOGD("Resetting and dropping all events (%s).", reason);
4914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
4916 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4917 synthesizeCancelationEventsForAllConnectionsLocked(options);
4918
4919 resetKeyRepeatLocked();
4920 releasePendingEventLocked();
4921 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004922 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004925 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004927 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928}
4929
4930void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004931 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 dumpDispatchStateLocked(dump);
4933
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004934 std::istringstream stream(dump);
4935 std::string line;
4936
4937 while (std::getline(stream, line, '\n')) {
4938 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 }
4940}
4941
Prabir Pradhan99987712020-11-10 18:43:05 -08004942std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4943 std::string dump;
4944
4945 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4946 toString(mFocusedWindowRequestedPointerCapture));
4947
4948 std::string windowName = "None";
4949 if (mWindowTokenWithPointerCapture) {
chaviw3277faf2021-05-19 16:45:23 -05004950 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004951 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4952 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4953 : "token has capture without window";
4954 }
4955 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4956
4957 return dump;
4958}
4959
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004960void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004961 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4962 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4963 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004964 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
Tiger Huang721e26f2018-07-24 22:26:19 +08004966 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4967 dump += StringPrintf(INDENT "FocusedApplications:\n");
4968 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4969 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004970 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004971 const std::chrono::duration timeout =
4972 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004973 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004974 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004975 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004978 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004980
Vishnu Nairc519ff72021-01-21 08:23:08 -08004981 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004982 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004984 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004985 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004986 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4987 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004988 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 state.displayId, toString(state.down), toString(state.split),
4990 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004991 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004992 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004993 for (size_t i = 0; i < state.windows.size(); i++) {
4994 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 dump += StringPrintf(INDENT4
4996 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4997 i, touchedWindow.windowHandle->getName().c_str(),
4998 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004999 }
5000 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005001 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005002 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005003 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005004 dump += INDENT3 "Portal windows:\n";
5005 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005006 const sp<WindowInfoHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5008 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005009 }
5010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005013 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015
arthurhung6d4bed92021-03-17 11:59:33 +08005016 if (mDragState) {
5017 dump += StringPrintf(INDENT "DragState:\n");
5018 mDragState->dump(dump, INDENT2);
5019 }
5020
Arthur Hungb92218b2018-08-14 12:00:21 +08005021 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05005023 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005024 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005025 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005026 dump += INDENT2 "Windows:\n";
5027 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005028 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5029 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005031 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005032 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005033 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005034 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005035 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005036 "applicationInfo.name=%s, "
5037 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005038 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005039 i, windowInfo->name.c_str(), windowInfo->id,
5040 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005042 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005043 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005044 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005045 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005046 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005047 windowInfo->frameLeft, windowInfo->frameTop,
5048 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005049 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005050 windowInfo->applicationInfo.name.c_str(),
5051 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005052 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005053 dump += StringPrintf(", inputFeatures=%s",
5054 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005055 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005056 "ms, trustedOverlay=%s, hasToken=%s, "
5057 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005059 millis(windowInfo->dispatchingTimeout),
5060 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005061 toString(windowInfo->token != nullptr),
5062 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005063 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005064 }
5065 } else {
5066 dump += INDENT2 "Windows: <none>\n";
5067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 }
5069 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005070 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
5072
Michael Wright3dd60e22019-03-27 22:06:44 +00005073 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005074 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 const std::vector<Monitor>& monitors = it.second;
5076 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5077 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005078 }
5079 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005080 const std::vector<Monitor>& monitors = it.second;
5081 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5082 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005085 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087
5088 nsecs_t currentTime = now();
5089
5090 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005091 if (!mRecentQueue.empty()) {
5092 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005093 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005094 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005095 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005096 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 }
5098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101
5102 // Dump event currently being dispatched.
5103 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005104 dump += INDENT "PendingEvent:\n";
5105 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005106 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005107 dump += StringPrintf(", age=%" PRId64 "ms\n",
5108 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005110 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 }
5112
5113 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005114 if (!mInboundQueue.empty()) {
5115 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005116 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005117 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005118 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005119 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 }
5121 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005122 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 }
5124
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005125 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005126 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005127 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5128 const KeyReplacement& replacement = pair.first;
5129 int32_t newKeyCode = pair.second;
5130 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005131 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005132 }
5133 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005134 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005135 }
5136
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005137 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005138 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005139 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005141 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005142 connection->inputChannel->getFd().get(),
5143 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005144 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005145 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005147 if (!connection->outboundQueue.empty()) {
5148 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5149 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005150 dump += dumpQueue(connection->outboundQueue, currentTime);
5151
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005153 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005156 if (!connection->waitQueue.empty()) {
5157 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5158 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005159 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005161 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163 }
5164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167
5168 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5170 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005175 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005176 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5177 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5178 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005179 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005180 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
Michael Wright3dd60e22019-03-27 22:06:44 +00005183void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5184 const size_t numMonitors = monitors.size();
5185 for (size_t i = 0; i < numMonitors; i++) {
5186 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005187 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005188 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5189 dump += "\n";
5190 }
5191}
5192
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005193class LooperEventCallback : public LooperCallback {
5194public:
5195 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5196 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5197
5198private:
5199 std::function<int(int events)> mCallback;
5200};
5201
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005202Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005203#if DEBUG_CHANNEL_CREATION
5204 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205#endif
5206
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005207 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005208 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005209 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005210
5211 if (result) {
5212 return base::Error(result) << "Failed to open input channel pair with name " << name;
5213 }
5214
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005216 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005217 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005218 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005219 sp<Connection> connection =
5220 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005222 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5223 ALOGE("Created a new connection, but the token %p is already known", token.get());
5224 }
5225 mConnectionsByToken.emplace(token, connection);
5226
5227 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5228 this, std::placeholders::_1, token);
5229
5230 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 } // release lock
5232
5233 // Wake the looper because some connections have changed.
5234 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005235 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236}
5237
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005238Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5239 bool isGestureMonitor,
5240 const std::string& name,
5241 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005242 std::shared_ptr<InputChannel> serverChannel;
5243 std::unique_ptr<InputChannel> clientChannel;
5244 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5245 if (result) {
5246 return base::Error(result) << "Failed to open input channel pair with name " << name;
5247 }
5248
Michael Wright3dd60e22019-03-27 22:06:44 +00005249 { // acquire lock
5250 std::scoped_lock _l(mLock);
5251
5252 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005253 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5254 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005255 }
5256
Garfield Tan15601662020-09-22 15:32:38 -07005257 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005258 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005259 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005260
5261 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5262 ALOGE("Created a new connection, but the token %p is already known", token.get());
5263 }
5264 mConnectionsByToken.emplace(token, connection);
5265 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5266 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 auto& monitorsByDisplay =
5269 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005270 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005271
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005273 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5274 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005275 }
Garfield Tan15601662020-09-22 15:32:38 -07005276
Michael Wright3dd60e22019-03-27 22:06:44 +00005277 // Wake the looper because some connections have changed.
5278 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005279 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005280}
5281
Garfield Tan15601662020-09-22 15:32:38 -07005282status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005284 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285
Garfield Tan15601662020-09-22 15:32:38 -07005286 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 if (status) {
5288 return status;
5289 }
5290 } // release lock
5291
5292 // Wake the poll loop because removing the connection may have changed the current
5293 // synchronization state.
5294 mLooper->wake();
5295 return OK;
5296}
5297
Garfield Tan15601662020-09-22 15:32:38 -07005298status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5299 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005300 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005301 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005302 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 return BAD_VALUE;
5304 }
5305
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005306 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005307
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005309 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005312 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 nsecs_t currentTime = now();
5315 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5316
5317 connection->status = Connection::STATUS_ZOMBIE;
5318 return OK;
5319}
5320
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005321void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5322 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5323 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005324}
5325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005326void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005327 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005328 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005329 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005330 std::vector<Monitor>& monitors = it->second;
5331 const size_t numMonitors = monitors.size();
5332 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005333 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005334 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5335 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005336 monitors.erase(monitors.begin() + i);
5337 break;
5338 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005339 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 if (monitors.empty()) {
5341 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005342 } else {
5343 ++it;
5344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 }
5346}
5347
Michael Wright3dd60e22019-03-27 22:06:44 +00005348status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5349 { // acquire lock
5350 std::scoped_lock _l(mLock);
5351 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5352
5353 if (!foundDisplayId) {
5354 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5355 return BAD_VALUE;
5356 }
5357 int32_t displayId = foundDisplayId.value();
5358
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005359 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5360 mTouchStatesByDisplay.find(displayId);
5361 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005362 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5363 return BAD_VALUE;
5364 }
5365
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005366 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005367 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005368 std::optional<int32_t> foundDeviceId;
5369 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005370 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005371 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005372 foundDeviceId = state.deviceId;
5373 }
5374 }
5375 if (!foundDeviceId || !state.down) {
5376 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005377 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005378 return BAD_VALUE;
5379 }
5380 int32_t deviceId = foundDeviceId.value();
5381
5382 // Send cancel events to all the input channels we're stealing from.
5383 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 options.deviceId = deviceId;
5386 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005387 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005388 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005389 std::shared_ptr<InputChannel> channel =
5390 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005391 if (channel != nullptr) {
5392 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005393 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005394 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005395 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005396 canceledWindows += "]";
5397 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5398 canceledWindows.c_str());
5399
Michael Wright3dd60e22019-03-27 22:06:44 +00005400 // Then clear the current touch state so we stop dispatching to them as well.
5401 state.filterNonMonitors();
5402 }
5403 return OK;
5404}
5405
Prabir Pradhan99987712020-11-10 18:43:05 -08005406void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5407 { // acquire lock
5408 std::scoped_lock _l(mLock);
5409 if (DEBUG_FOCUS) {
chaviw3277faf2021-05-19 16:45:23 -05005410 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005411 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5412 windowHandle != nullptr ? windowHandle->getName().c_str()
5413 : "token without window");
5414 }
5415
Vishnu Nairc519ff72021-01-21 08:23:08 -08005416 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005417 if (focusedToken != windowToken) {
5418 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5419 enabled ? "enable" : "disable");
5420 return;
5421 }
5422
5423 if (enabled == mFocusedWindowRequestedPointerCapture) {
5424 ALOGW("Ignoring request to %s Pointer Capture: "
5425 "window has %s requested pointer capture.",
5426 enabled ? "enable" : "disable", enabled ? "already" : "not");
5427 return;
5428 }
5429
5430 mFocusedWindowRequestedPointerCapture = enabled;
5431 setPointerCaptureLocked(enabled);
5432 } // release lock
5433
5434 // Wake the thread to process command entries.
5435 mLooper->wake();
5436}
5437
Michael Wright3dd60e22019-03-27 22:06:44 +00005438std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5439 const sp<IBinder>& token) {
5440 for (const auto& it : mGestureMonitorsByDisplay) {
5441 const std::vector<Monitor>& monitors = it.second;
5442 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005443 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005444 return it.first;
5445 }
5446 }
5447 }
5448 return std::nullopt;
5449}
5450
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005451std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5452 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5453 if (gesturePid.has_value()) {
5454 return gesturePid;
5455 }
5456 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5457}
5458
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005459sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005460 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005461 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005462 }
5463
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005464 for (const auto& [token, connection] : mConnectionsByToken) {
5465 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005466 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 }
5468 }
Robert Carr4e670e52018-08-15 13:26:12 -07005469
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005470 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471}
5472
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005473std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5474 sp<Connection> connection = getConnectionLocked(connectionToken);
5475 if (connection == nullptr) {
5476 return "<nullptr>";
5477 }
5478 return connection->getInputChannelName();
5479}
5480
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005481void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005482 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005483 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005484}
5485
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005486void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5487 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005488 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005489 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5490 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 commandEntry->connection = connection;
5492 commandEntry->eventTime = currentTime;
5493 commandEntry->seq = seq;
5494 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005495 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005496 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497}
5498
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005499void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5500 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005502 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005504 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5505 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005507 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508}
5509
Vishnu Nairad321cd2020-08-20 16:40:21 -07005510void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5511 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005512 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5513 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005514 commandEntry->oldToken = oldToken;
5515 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005516 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005517}
5518
arthurhungf452d0b2021-01-06 00:19:52 +08005519void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5520 std::unique_ptr<CommandEntry> commandEntry =
5521 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5522 commandEntry->newToken = token;
5523 commandEntry->x = x;
5524 commandEntry->y = y;
5525 postCommandLocked(std::move(commandEntry));
5526}
5527
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005528void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5529 if (connection == nullptr) {
5530 LOG_ALWAYS_FATAL("Caller must check for nullness");
5531 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005532 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5533 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005534 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005535 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005536 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005537 return;
5538 }
5539 /**
5540 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5541 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5542 * has changed. This could cause newer entries to time out before the already dispatched
5543 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5544 * processes the events linearly. So providing information about the oldest entry seems to be
5545 * most useful.
5546 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005547 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005548 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5549 std::string reason =
5550 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005551 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005552 ns2ms(currentWait),
5553 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005554 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005555 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005556
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005557 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5558
5559 // Stop waking up for events on this connection, it is already unresponsive
5560 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005561}
5562
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005563void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5564 std::string reason =
5565 StringPrintf("%s does not have a focused window", application->getName().c_str());
5566 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005567
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005568 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5569 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5570 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005571 postCommandLocked(std::move(commandEntry));
5572}
5573
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005574void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5575 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5576 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5577 commandEntry->obscuringPackage = obscuringPackage;
5578 postCommandLocked(std::move(commandEntry));
5579}
5580
chaviw3277faf2021-05-19 16:45:23 -05005581void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005582 const std::string& reason) {
5583 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5584 updateLastAnrStateLocked(windowLabel, reason);
5585}
5586
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005587void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5588 const std::string& reason) {
5589 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005590 updateLastAnrStateLocked(windowLabel, reason);
5591}
5592
5593void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5594 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005596 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 struct tm tm;
5598 localtime_r(&t, &tm);
5599 char timestr[64];
5600 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005601 mLastAnrState.clear();
5602 mLastAnrState += INDENT "ANR:\n";
5603 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005604 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5605 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005606 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607}
5608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005609void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 mLock.unlock();
5611
5612 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5613
5614 mLock.lock();
5615}
5616
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005617void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 sp<Connection> connection = commandEntry->connection;
5619
5620 if (connection->status != Connection::STATUS_ZOMBIE) {
5621 mLock.unlock();
5622
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005623 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624
5625 mLock.lock();
5626 }
5627}
5628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005629void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005630 sp<IBinder> oldToken = commandEntry->oldToken;
5631 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005632 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005633 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005634 mLock.lock();
5635}
5636
arthurhungf452d0b2021-01-06 00:19:52 +08005637void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5638 sp<IBinder> newToken = commandEntry->newToken;
5639 mLock.unlock();
5640 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5641 mLock.lock();
5642}
5643
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005644void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005646
5647 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5648
5649 mLock.lock();
5650}
5651
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005652void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005653 mLock.unlock();
5654
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005655 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656
5657 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005658}
5659
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005660void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005661 mLock.unlock();
5662
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005663 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5664
5665 mLock.lock();
5666}
5667
5668void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5669 mLock.unlock();
5670
5671 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5672
5673 mLock.lock();
5674}
5675
5676void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5677 mLock.unlock();
5678
5679 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005680
5681 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005682}
5683
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005684void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5685 mLock.unlock();
5686
5687 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5688
5689 mLock.lock();
5690}
5691
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5693 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005694 KeyEntry& entry = *(commandEntry->keyEntry);
5695 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696
5697 mLock.unlock();
5698
Michael Wright2b3c3302018-03-02 17:19:13 +00005699 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005700 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005701 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005702 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5703 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005704 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706
5707 mLock.lock();
5708
5709 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005710 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005712 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005714 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5715 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717}
5718
chaviwfd6d3512019-03-25 13:23:49 -07005719void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5720 mLock.unlock();
5721 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5722 mLock.lock();
5723}
5724
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005725/**
5726 * Connection is responsive if it has no events in the waitQueue that are older than the
5727 * current time.
5728 */
5729static bool isConnectionResponsive(const Connection& connection) {
5730 const nsecs_t currentTime = now();
5731 for (const DispatchEntry* entry : connection.waitQueue) {
5732 if (entry->timeoutTime < currentTime) {
5733 return false;
5734 }
5735 }
5736 return true;
5737}
5738
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005739void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005741 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005743 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744
5745 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005746 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005747 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005748 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005750 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005751 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005752 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005753 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5754 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005755 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005756 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5757 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5758 connection->inputChannel->getConnectionToken(),
5759 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5760 finishTime);
5761 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005762
5763 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005764 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005765 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005766 restartEvent =
5767 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005768 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005769 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005770 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5771 handled);
5772 } else {
5773 restartEvent = false;
5774 }
5775
5776 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005777 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005778 // contents of the wait queue to have been drained, so we need to double-check
5779 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005780 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5781 if (dispatchEntryIt != connection->waitQueue.end()) {
5782 dispatchEntry = *dispatchEntryIt;
5783 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005784 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5785 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005786 if (!connection->responsive) {
5787 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005788 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005789 // The connection was unresponsive, and now it's responsive.
5790 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005791 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005792 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005793 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005794 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005795 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005796 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005797 } else {
5798 releaseDispatchEntry(dispatchEntry);
5799 }
5800 }
5801
5802 // Start the next dispatch cycle for this connection.
5803 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804}
5805
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005806void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5807 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5808 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5809 monitorUnresponsiveCommand->pid = pid;
5810 monitorUnresponsiveCommand->reason = std::move(reason);
5811 postCommandLocked(std::move(monitorUnresponsiveCommand));
5812}
5813
5814void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5815 std::string reason) {
5816 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5817 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5818 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5819 windowUnresponsiveCommand->reason = std::move(reason);
5820 postCommandLocked(std::move(windowUnresponsiveCommand));
5821}
5822
5823void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5824 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5825 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5826 monitorResponsiveCommand->pid = pid;
5827 postCommandLocked(std::move(monitorResponsiveCommand));
5828}
5829
5830void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5831 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5832 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5833 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5834 postCommandLocked(std::move(windowResponsiveCommand));
5835}
5836
5837/**
5838 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5839 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5840 * command entry to the command queue.
5841 */
5842void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5843 std::string reason) {
5844 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5845 if (connection.monitor) {
5846 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5847 reason.c_str());
5848 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5849 if (!pid.has_value()) {
5850 ALOGE("Could not find unresponsive monitor for connection %s",
5851 connection.inputChannel->getName().c_str());
5852 return;
5853 }
5854 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5855 return;
5856 }
5857 // If not a monitor, must be a window
5858 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5859 reason.c_str());
5860 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5861}
5862
5863/**
5864 * Tell the policy that a connection has become responsive so that it can stop ANR.
5865 */
5866void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5867 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5868 if (connection.monitor) {
5869 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5870 if (!pid.has_value()) {
5871 ALOGE("Could not find responsive monitor for connection %s",
5872 connection.inputChannel->getName().c_str());
5873 return;
5874 }
5875 sendMonitorResponsiveCommandLocked(pid.value());
5876 return;
5877 }
5878 // If not a monitor, must be a window
5879 sendWindowResponsiveCommandLocked(connectionToken);
5880}
5881
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005883 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005884 KeyEntry& keyEntry, bool handled) {
5885 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005886 if (!handled) {
5887 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005888 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005889 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005890 return false;
5891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005893 // Get the fallback key state.
5894 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005895 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005896 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005897 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005898 connection->inputState.removeFallbackKey(originalKeyCode);
5899 }
5900
5901 if (handled || !dispatchEntry->hasForegroundTarget()) {
5902 // If the application handles the original key for which we previously
5903 // generated a fallback or if the window is not a foreground window,
5904 // then cancel the associated fallback key, if any.
5905 if (fallbackKeyCode != -1) {
5906 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005908 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005909 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005910 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005912 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005913 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914
5915 mLock.unlock();
5916
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005917 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919
5920 mLock.lock();
5921
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922 // Cancel the fallback key.
5923 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005925 "application handled the original non-fallback key "
5926 "or is no longer a foreground target, "
5927 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928 options.keyCode = fallbackKeyCode;
5929 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005931 connection->inputState.removeFallbackKey(originalKeyCode);
5932 }
5933 } else {
5934 // If the application did not handle a non-fallback key, first check
5935 // that we are in a good state to perform unhandled key event processing
5936 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005937 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005938 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005941 "since this is not an initial down. "
5942 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005943 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005945 return false;
5946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948 // Dispatch the unhandled key to the policy.
5949#if DEBUG_OUTBOUND_EVENT_DETAILS
5950 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005951 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005952 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005953#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005954 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955
5956 mLock.unlock();
5957
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005958 bool fallback =
5959 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005960 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005961
5962 mLock.lock();
5963
5964 if (connection->status != Connection::STATUS_NORMAL) {
5965 connection->inputState.removeFallbackKey(originalKeyCode);
5966 return false;
5967 }
5968
5969 // Latch the fallback keycode for this key on an initial down.
5970 // The fallback keycode cannot change at any other point in the lifecycle.
5971 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973 fallbackKeyCode = event.getKeyCode();
5974 } else {
5975 fallbackKeyCode = AKEYCODE_UNKNOWN;
5976 }
5977 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5978 }
5979
5980 ALOG_ASSERT(fallbackKeyCode != -1);
5981
5982 // Cancel the fallback key if the policy decides not to send it anymore.
5983 // We will continue to dispatch the key to the policy but we will no
5984 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005985 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5986 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005987#if DEBUG_OUTBOUND_EVENT_DETAILS
5988 if (fallback) {
5989 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005990 "as a fallback for %d, but on the DOWN it had requested "
5991 "to send %d instead. Fallback canceled.",
5992 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 } else {
5994 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005995 "but on the DOWN it had requested to send %d. "
5996 "Fallback canceled.",
5997 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005998 }
5999#endif
6000
6001 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6002 "canceling fallback, policy no longer desires it");
6003 options.keyCode = fallbackKeyCode;
6004 synthesizeCancelationEventsForConnectionLocked(connection, options);
6005
6006 fallback = false;
6007 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006008 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006009 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 }
6011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012
6013#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006014 {
6015 std::string msg;
6016 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6017 connection->inputState.getFallbackKeys();
6018 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006019 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006021 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006022 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006023 }
6024#endif
6025
6026 if (fallback) {
6027 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006028 keyEntry.eventTime = event.getEventTime();
6029 keyEntry.deviceId = event.getDeviceId();
6030 keyEntry.source = event.getSource();
6031 keyEntry.displayId = event.getDisplayId();
6032 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6033 keyEntry.keyCode = fallbackKeyCode;
6034 keyEntry.scanCode = event.getScanCode();
6035 keyEntry.metaState = event.getMetaState();
6036 keyEntry.repeatCount = event.getRepeatCount();
6037 keyEntry.downTime = event.getDownTime();
6038 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006039
6040#if DEBUG_OUTBOUND_EVENT_DETAILS
6041 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006042 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006043 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044#endif
6045 return true; // restart the event
6046 } else {
6047#if DEBUG_OUTBOUND_EVENT_DETAILS
6048 ALOGD("Unhandled key event: No fallback key.");
6049#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006050
6051 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 }
6054 }
6055 return false;
6056}
6057
6058bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006059 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006060 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 return false;
6062}
6063
6064void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6065 mLock.unlock();
6066
Sean Stoutb4e0a592021-02-23 07:34:53 -08006067 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6068 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069
6070 mLock.lock();
6071}
6072
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073void InputDispatcher::traceInboundQueueLengthLocked() {
6074 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006075 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 }
6077}
6078
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006079void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080 if (ATRACE_ENABLED()) {
6081 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006082 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6083 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084 }
6085}
6086
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006087void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 if (ATRACE_ENABLED()) {
6089 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006090 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6091 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 }
6093}
6094
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006095void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006096 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006098 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 dumpDispatchStateLocked(dump);
6100
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006101 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006102 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006103 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006104 }
6105}
6106
6107void InputDispatcher::monitor() {
6108 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006109 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006110 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006111 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112}
6113
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006114/**
6115 * Wake up the dispatcher and wait until it processes all events and commands.
6116 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6117 * this method can be safely called from any thread, as long as you've ensured that
6118 * the work you are interested in completing has already been queued.
6119 */
6120bool InputDispatcher::waitForIdle() {
6121 /**
6122 * Timeout should represent the longest possible time that a device might spend processing
6123 * events and commands.
6124 */
6125 constexpr std::chrono::duration TIMEOUT = 100ms;
6126 std::unique_lock lock(mLock);
6127 mLooper->wake();
6128 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6129 return result == std::cv_status::no_timeout;
6130}
6131
Vishnu Naire798b472020-07-23 13:52:21 -07006132/**
6133 * Sets focus to the window identified by the token. This must be called
6134 * after updating any input window handles.
6135 *
6136 * Params:
6137 * request.token - input channel token used to identify the window that should gain focus.
6138 * request.focusedToken - the token that the caller expects currently to be focused. If the
6139 * specified token does not match the currently focused window, this request will be dropped.
6140 * If the specified focused token matches the currently focused window, the call will succeed.
6141 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6142 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6143 * when requesting the focus change. This determines which request gets
6144 * precedence if there is a focus change request from another source such as pointer down.
6145 */
Vishnu Nair958da932020-08-21 17:12:37 -07006146void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6147 { // acquire lock
6148 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006149 std::optional<FocusResolver::FocusChanges> changes =
6150 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6151 if (changes) {
6152 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006153 }
6154 } // release lock
6155 // Wake up poll loop since it may need to make new input dispatching choices.
6156 mLooper->wake();
6157}
6158
Vishnu Nairc519ff72021-01-21 08:23:08 -08006159void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6160 if (changes.oldFocus) {
6161 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006162 if (focusedInputChannel) {
6163 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6164 "focus left window");
6165 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006166 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006167 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006168 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006169 if (changes.newFocus) {
6170 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006171 }
6172
Prabir Pradhan99987712020-11-10 18:43:05 -08006173 // If a window has pointer capture, then it must have focus. We need to ensure that this
6174 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6175 // If the window loses focus before it loses pointer capture, then the window can be in a state
6176 // where it has pointer capture but not focus, violating the contract. Therefore we must
6177 // dispatch the pointer capture event before the focus event. Since focus events are added to
6178 // the front of the queue (above), we add the pointer capture event to the front of the queue
6179 // after the focus events are added. This ensures the pointer capture event ends up at the
6180 // front.
6181 disablePointerCaptureForcedLocked();
6182
Vishnu Nairc519ff72021-01-21 08:23:08 -08006183 if (mFocusedDisplayId == changes.displayId) {
6184 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006185 }
6186}
Vishnu Nair958da932020-08-21 17:12:37 -07006187
Prabir Pradhan99987712020-11-10 18:43:05 -08006188void InputDispatcher::disablePointerCaptureForcedLocked() {
6189 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6190 return;
6191 }
6192
6193 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6194
6195 if (mFocusedWindowRequestedPointerCapture) {
6196 mFocusedWindowRequestedPointerCapture = false;
6197 setPointerCaptureLocked(false);
6198 }
6199
6200 if (!mWindowTokenWithPointerCapture) {
6201 // No need to send capture changes because no window has capture.
6202 return;
6203 }
6204
6205 if (mPendingEvent != nullptr) {
6206 // Move the pending event to the front of the queue. This will give the chance
6207 // for the pending event to be dropped if it is a captured event.
6208 mInboundQueue.push_front(mPendingEvent);
6209 mPendingEvent = nullptr;
6210 }
6211
6212 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6213 false /* hasCapture */);
6214 mInboundQueue.push_front(std::move(entry));
6215}
6216
Prabir Pradhan99987712020-11-10 18:43:05 -08006217void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6218 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6219 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6220 commandEntry->enabled = enabled;
6221 postCommandLocked(std::move(commandEntry));
6222}
6223
6224void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6225 android::inputdispatcher::CommandEntry* commandEntry) {
6226 mLock.unlock();
6227
6228 mPolicy->setPointerCapture(commandEntry->enabled);
6229
6230 mLock.lock();
6231}
6232
Vishnu Nair599f1412021-06-21 10:39:58 -07006233void InputDispatcher::displayRemoved(int32_t displayId) {
6234 { // acquire lock
6235 std::scoped_lock _l(mLock);
6236 // Set an empty list to remove all handles from the specific display.
6237 setInputWindowsLocked(/* window handles */ {}, displayId);
6238 setFocusedApplicationLocked(displayId, nullptr);
6239 // Call focus resolver to clean up stale requests. This must be called after input windows
6240 // have been removed for the removed display.
6241 mFocusResolver.displayRemoved(displayId);
6242 } // release lock
6243
6244 // Wake up poll loop since it may need to make new input dispatching choices.
6245 mLooper->wake();
6246}
6247
Garfield Tane84e6f92019-08-29 17:28:41 -07006248} // namespace android::inputdispatcher