blob: 48357951fd43e223cf32d378d1632ef76c031ca7 [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*/,
334 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900335 }
336 }
337
chaviw1ff3d1e2020-07-01 15:53:47 -0700338 if (inputTarget.useDefaultPointerTransform()) {
339 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700340 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700341 inputTarget.globalScaleFactor,
342 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000343 }
344
345 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
346 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700348 std::vector<PointerCoords> pointerCoords;
349 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000350
351 // Use the first pointer information to normalize all other pointers. This could be any pointer
352 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 // uses the transform for the normalized pointer.
354 const ui::Transform& firstPointerTransform =
355 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
356 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357
358 // Iterate through all pointers in the event to normalize against the first.
359 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
360 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
361 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700362 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000363
364 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700365 // First, apply the current pointer's transform to update the coordinates into
366 // window space.
367 pointerCoords[pointerIndex].transform(currTransform);
368 // Next, apply the inverse transform of the normalized coordinates so the
369 // current coordinates are transformed into the normalized coordinate space.
370 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371 }
372
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700373 std::unique_ptr<MotionEntry> combinedMotionEntry =
374 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
375 motionEntry.deviceId, motionEntry.source,
376 motionEntry.displayId, motionEntry.policyFlags,
377 motionEntry.action, motionEntry.actionButton,
378 motionEntry.flags, motionEntry.metaState,
379 motionEntry.buttonState, motionEntry.classification,
380 motionEntry.edgeFlags, motionEntry.xPrecision,
381 motionEntry.yPrecision, motionEntry.xCursorPosition,
382 motionEntry.yCursorPosition, motionEntry.downTime,
383 motionEntry.pointerCount, motionEntry.pointerProperties,
384 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000385
386 if (motionEntry.injectionState) {
387 combinedMotionEntry->injectionState = motionEntry.injectionState;
388 combinedMotionEntry->injectionState->refCount += 1;
389 }
390
391 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700392 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700393 firstPointerTransform, inputTarget.globalScaleFactor,
394 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000395 return dispatchEntry;
396}
397
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700398static void addGestureMonitors(const std::vector<Monitor>& monitors,
399 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
400 float yOffset = 0) {
401 if (monitors.empty()) {
402 return;
403 }
404 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
405 for (const Monitor& monitor : monitors) {
406 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
407 }
408}
409
Garfield Tan15601662020-09-22 15:32:38 -0700410static status_t openInputChannelPair(const std::string& name,
411 std::shared_ptr<InputChannel>& serverChannel,
412 std::unique_ptr<InputChannel>& clientChannel) {
413 std::unique_ptr<InputChannel> uniqueServerChannel;
414 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
415
416 serverChannel = std::move(uniqueServerChannel);
417 return result;
418}
419
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500420template <typename T>
421static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
422 if (lhs == nullptr && rhs == nullptr) {
423 return true;
424 }
425 if (lhs == nullptr || rhs == nullptr) {
426 return false;
427 }
428 return *lhs == *rhs;
429}
430
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000431static sp<IPlatformCompatNative> getCompatService() {
432 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
433 if (service == nullptr) {
434 ALOGE("Failed to link to compat service");
435 return nullptr;
436 }
437 return interface_cast<IPlatformCompatNative>(service);
438}
439
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000440static KeyEvent createKeyEvent(const KeyEntry& entry) {
441 KeyEvent event;
442 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
443 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
444 entry.repeatCount, entry.downTime, entry.eventTime);
445 return event;
446}
447
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000448static std::optional<int32_t> findMonitorPidByToken(
449 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
450 const sp<IBinder>& token) {
451 for (const auto& it : monitorsByDisplay) {
452 const std::vector<Monitor>& monitors = it.second;
453 for (const Monitor& monitor : monitors) {
454 if (monitor.inputChannel->getConnectionToken() == token) {
455 return monitor.pid;
456 }
457 }
458 }
459 return std::nullopt;
460}
461
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000462static bool shouldReportMetricsForConnection(const Connection& connection) {
463 // Do not keep track of gesture monitors. They receive every event and would disproportionately
464 // affect the statistics.
465 if (connection.monitor) {
466 return false;
467 }
468 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
469 if (!connection.responsive) {
470 return false;
471 }
472 return true;
473}
474
475static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
476 const Connection& connection) {
477 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
478 const int32_t& inputEventId = eventEntry.id;
479 if (inputEventId != dispatchEntry.resolvedEventId) {
480 // Event was transmuted
481 return false;
482 }
483 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
484 return false;
485 }
486 // Only track latency for events that originated from hardware
487 if (eventEntry.isSynthesized()) {
488 return false;
489 }
490 const EventEntry::Type& inputEventEntryType = eventEntry.type;
491 if (inputEventEntryType == EventEntry::Type::KEY) {
492 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
493 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
494 return false;
495 }
496 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
497 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
498 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
499 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
500 return false;
501 }
502 } else {
503 // Not a key or a motion
504 return false;
505 }
506 if (!shouldReportMetricsForConnection(connection)) {
507 return false;
508 }
509 return true;
510}
511
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512// --- InputDispatcher ---
513
Garfield Tan00f511d2019-06-12 16:55:40 -0700514InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
515 : mPolicy(policy),
516 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700517 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800518 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700519 mAppSwitchSawKeyDown(false),
520 mAppSwitchDueTime(LONG_LONG_MAX),
521 mNextUnblockedEvent(nullptr),
522 mDispatchEnabled(false),
523 mDispatchFrozen(false),
524 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800525 // mInTouchMode will be initialized by the WindowManager to the default device config.
526 // To avoid leaking stack in case that call never comes, and for tests,
527 // initialize it here anyways.
528 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100529 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000530 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800531 mFocusedWindowRequestedPointerCapture(false),
532 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000533 mLatencyAggregator(),
534 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000535 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800537 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800538
Yi Kong9b14ac62018-07-17 13:48:38 -0700539 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540
541 policy->getDispatcherConfiguration(&mConfig);
542}
543
544InputDispatcher::~InputDispatcher() {
545 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800546 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547
548 resetKeyRepeatLocked();
549 releasePendingEventLocked();
550 drainInboundQueueLocked();
551 }
552
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000553 while (!mConnectionsByToken.empty()) {
554 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700555 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 }
557}
558
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700559status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700560 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700561 return ALREADY_EXISTS;
562 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700563 mThread = std::make_unique<InputThread>(
564 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
565 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700566}
567
568status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700569 if (mThread && mThread->isCallingThread()) {
570 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700571 return INVALID_OPERATION;
572 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700573 mThread.reset();
574 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700575}
576
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577void InputDispatcher::dispatchOnce() {
578 nsecs_t nextWakeupTime = LONG_LONG_MAX;
579 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800580 std::scoped_lock _l(mLock);
581 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582
583 // Run a dispatch loop if there are no pending commands.
584 // The dispatch loop might enqueue commands to run afterwards.
585 if (!haveCommandsLocked()) {
586 dispatchOnceInnerLocked(&nextWakeupTime);
587 }
588
589 // Run all pending commands if there are any.
590 // If any commands were run then force the next poll to wake up immediately.
591 if (runCommandsLockedInterruptible()) {
592 nextWakeupTime = LONG_LONG_MIN;
593 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800594
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700595 // If we are still waiting for ack on some events,
596 // we might have to wake up earlier to check if an app is anr'ing.
597 const nsecs_t nextAnrCheck = processAnrsLocked();
598 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
599
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800600 // We are about to enter an infinitely long sleep, because we have no commands or
601 // pending or queued events
602 if (nextWakeupTime == LONG_LONG_MAX) {
603 mDispatcherEnteredIdle.notify_all();
604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 } // release lock
606
607 // Wait for callback or timeout or wake. (make sure we round up, not down)
608 nsecs_t currentTime = now();
609 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
610 mLooper->pollOnce(timeoutMillis);
611}
612
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700613/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500614 * Raise ANR if there is no focused window.
615 * Before the ANR is raised, do a final state check:
616 * 1. The currently focused application must be the same one we are waiting for.
617 * 2. Ensure we still don't have a focused window.
618 */
619void InputDispatcher::processNoFocusedWindowAnrLocked() {
620 // Check if the application that we are waiting for is still focused.
621 std::shared_ptr<InputApplicationHandle> focusedApplication =
622 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
623 if (focusedApplication == nullptr ||
624 focusedApplication->getApplicationToken() !=
625 mAwaitedFocusedApplication->getApplicationToken()) {
626 // Unexpected because we should have reset the ANR timer when focused application changed
627 ALOGE("Waited for a focused window, but focused application has already changed to %s",
628 focusedApplication->getName().c_str());
629 return; // The focused application has changed.
630 }
631
chaviw3277faf2021-05-19 16:45:23 -0500632 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500633 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
634 if (focusedWindowHandle != nullptr) {
635 return; // We now have a focused window. No need for ANR.
636 }
637 onAnrLocked(mAwaitedFocusedApplication);
638}
639
640/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700641 * Check if any of the connections' wait queues have events that are too old.
642 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
643 * Return the time at which we should wake up next.
644 */
645nsecs_t InputDispatcher::processAnrsLocked() {
646 const nsecs_t currentTime = now();
647 nsecs_t nextAnrCheck = LONG_LONG_MAX;
648 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
649 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
650 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500651 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700652 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500653 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700654 return LONG_LONG_MIN;
655 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500656 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700657 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
658 }
659 }
660
661 // Check if any connection ANRs are due
662 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
663 if (currentTime < nextAnrCheck) { // most likely scenario
664 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
665 }
666
667 // If we reached here, we have an unresponsive connection.
668 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
669 if (connection == nullptr) {
670 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
671 return nextAnrCheck;
672 }
673 connection->responsive = false;
674 // Stop waking up for this unresponsive connection
675 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000676 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700677 return LONG_LONG_MIN;
678}
679
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500680std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw3277faf2021-05-19 16:45:23 -0500681 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700682 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500683 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700684 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500685 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700686}
687
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
689 nsecs_t currentTime = now();
690
Jeff Browndc5992e2014-04-11 01:27:26 -0700691 // Reset the key repeat timer whenever normal dispatch is suspended while the
692 // device is in a non-interactive state. This is to ensure that we abort a key
693 // repeat if the device is just coming out of sleep.
694 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 resetKeyRepeatLocked();
696 }
697
698 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
699 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100700 if (DEBUG_FOCUS) {
701 ALOGD("Dispatch frozen. Waiting some more.");
702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 return;
704 }
705
706 // Optimize latency of app switches.
707 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
708 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
709 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
710 if (mAppSwitchDueTime < *nextWakeupTime) {
711 *nextWakeupTime = mAppSwitchDueTime;
712 }
713
714 // Ready to start a new event.
715 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700717 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 if (isAppSwitchDue) {
719 // The inbound queue is empty so the app switch key we were waiting
720 // for will never arrive. Stop waiting for it.
721 resetPendingAppSwitchLocked(false);
722 isAppSwitchDue = false;
723 }
724
725 // Synthesize a key repeat if appropriate.
726 if (mKeyRepeatState.lastKeyEntry) {
727 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
728 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
729 } else {
730 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
731 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
732 }
733 }
734 }
735
736 // Nothing to do if there is no pending event.
737 if (!mPendingEvent) {
738 return;
739 }
740 } else {
741 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700742 mPendingEvent = mInboundQueue.front();
743 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 traceInboundQueueLengthLocked();
745 }
746
747 // Poke user activity for this event.
748 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700749 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 }
752
753 // Now we have an event to dispatch.
754 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700755 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700757 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700759 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700761 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 }
763
764 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700765 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 }
767
768 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700769 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700770 const ConfigurationChangedEntry& typedEntry =
771 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700772 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 break;
775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700777 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700778 const DeviceResetEntry& typedEntry =
779 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 break;
783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100785 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700786 std::shared_ptr<FocusEntry> typedEntry =
787 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100788 dispatchFocusLocked(currentTime, typedEntry);
789 done = true;
790 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
791 break;
792 }
793
Prabir Pradhan99987712020-11-10 18:43:05 -0800794 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
795 const auto typedEntry =
796 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
797 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
798 done = true;
799 break;
800 }
801
arthurhungb89ccb02020-12-30 16:19:01 +0800802 case EventEntry::Type::DRAG: {
803 std::shared_ptr<DragEntry> typedEntry =
804 std::static_pointer_cast<DragEntry>(mPendingEvent);
805 dispatchDragLocked(currentTime, typedEntry);
806 done = true;
807 break;
808 }
809
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700810 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700811 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700813 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 resetPendingAppSwitchLocked(true);
815 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 } else if (dropReason == DropReason::NOT_DROPPED) {
817 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 }
819 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700821 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700823 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
824 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700826 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 break;
828 }
829
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700830 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700831 std::shared_ptr<MotionEntry> motionEntry =
832 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700833 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
834 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700836 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700837 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700839 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
840 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700841 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700842 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 }
Chris Yef59a2f42020-10-16 12:55:26 -0700845
846 case EventEntry::Type::SENSOR: {
847 std::shared_ptr<SensorEntry> sensorEntry =
848 std::static_pointer_cast<SensorEntry>(mPendingEvent);
849 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
850 dropReason = DropReason::APP_SWITCH;
851 }
852 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
853 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
854 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
855 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
856 dropReason = DropReason::STALE;
857 }
858 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
859 done = true;
860 break;
861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
863
864 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700866 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
Michael Wright3a981722015-06-10 15:26:13 +0100868 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869
870 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 }
873}
874
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700875/**
876 * Return true if the events preceding this incoming motion event should be dropped
877 * Return false otherwise (the default behaviour)
878 */
879bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700880 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700881 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700882
883 // Optimize case where the current application is unresponsive and the user
884 // decides to touch a window in a different application.
885 // If the application takes too long to catch up then we drop all events preceding
886 // the touch into the other window.
887 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700888 int32_t displayId = motionEntry.displayId;
889 int32_t x = static_cast<int32_t>(
890 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
891 int32_t y = static_cast<int32_t>(
892 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw3277faf2021-05-19 16:45:23 -0500893 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700894 findTouchedWindowAtLocked(displayId, x, y, nullptr);
895 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700896 touchedWindowHandle->getApplicationToken() !=
897 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700898 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 ALOGI("Pruning input queue because user touched a different application while waiting "
900 "for %s",
901 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700902 return true;
903 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700904
905 // Alternatively, maybe there's a gesture monitor that could handle this event
906 std::vector<TouchedMonitor> gestureMonitors =
907 findTouchedGestureMonitorsLocked(displayId, {});
908 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
909 sp<Connection> connection =
910 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000911 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912 // This monitor could take more input. Drop all events preceding this
913 // event, so that gesture monitor could get a chance to receive the stream
914 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
915 "responsive gesture monitor that may handle the event",
916 mAwaitedFocusedApplication->getName().c_str());
917 return true;
918 }
919 }
920 }
921
922 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
923 // yet been processed by some connections, the dispatcher will wait for these motion
924 // events to be processed before dispatching the key event. This is because these motion events
925 // may cause a new window to be launched, which the user might expect to receive focus.
926 // To prevent waiting forever for such events, just send the key to the currently focused window
927 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
928 ALOGD("Received a new pointer down event, stop waiting for events to process and "
929 "just send the pending key event to the focused window.");
930 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700931 }
932 return false;
933}
934
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700935bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700936 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700937 mInboundQueue.push_back(std::move(newEntry));
938 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 traceInboundQueueLengthLocked();
940
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700941 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700942 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 // Optimize app switch latency.
944 // If the application takes too long to catch up then we drop all events preceding
945 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700946 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700948 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700950 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700955 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 mAppSwitchSawKeyDown = false;
957 needWake = true;
958 }
959 }
960 }
961 break;
962 }
963
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700964 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700965 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
966 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700967 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100971 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700972 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
973 break;
974 }
975 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800976 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700977 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800978 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
979 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700980 // nothing to do
981 break;
982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 }
984
985 return needWake;
986}
987
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700988void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700989 // Do not store sensor event in recent queue to avoid flooding the queue.
990 if (entry->type != EventEntry::Type::SENSOR) {
991 mRecentQueue.push_back(entry);
992 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700993 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700994 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 }
996}
997
chaviw3277faf2021-05-19 16:45:23 -0500998sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
999 int32_t y, TouchState* touchState,
1000 bool addOutsideTargets,
1001 bool addPortalWindows,
1002 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001003 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
1004 LOG_ALWAYS_FATAL(
1005 "Must provide a valid touch state if adding portal windows or outside targets");
1006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 // Traverse windows from front to back to find touched window.
chaviw3277faf2021-05-19 16:45:23 -05001008 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1009 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001010 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001011 continue;
1012 }
chaviw3277faf2021-05-19 16:45:23 -05001013 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001015 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016
1017 if (windowInfo->visible) {
chaviw3277faf2021-05-19 16:45:23 -05001018 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1019 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1020 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001022 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001023 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1024 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001025 if (addPortalWindows) {
1026 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001027 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001028 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001029 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 // Found window.
1033 return windowHandle;
1034 }
1035 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001036
chaviw3277faf2021-05-19 16:45:23 -05001037 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001038 touchState->addOrUpdateWindow(windowHandle,
1039 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1040 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 }
1044 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001045 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046}
1047
Garfield Tane84e6f92019-08-29 17:28:41 -07001048std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
chaviw3277faf2021-05-19 16:45:23 -05001049 int32_t displayId, const std::vector<sp<WindowInfoHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001050 std::vector<TouchedMonitor> touchedMonitors;
1051
1052 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1053 addGestureMonitors(monitors, touchedMonitors);
chaviw3277faf2021-05-19 16:45:23 -05001054 for (const sp<WindowInfoHandle>& portalWindow : portalWindows) {
1055 const WindowInfo* windowInfo = portalWindow->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001056 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1058 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001059 }
1060 return touchedMonitors;
1061}
1062
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001063void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 const char* reason;
1065 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 reason = "inbound event was dropped because the policy consumed it";
1071 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 case DropReason::DISABLED:
1073 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 ALOGI("Dropped event because input dispatch is disabled.");
1075 }
1076 reason = "inbound event was dropped because input dispatch is disabled";
1077 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 ALOGI("Dropped event because of pending overdue app switch.");
1080 reason = "inbound event was dropped because of pending overdue app switch";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 ALOGI("Dropped event because the current application is not responding and the user "
1084 "has started interacting with a different application.");
1085 reason = "inbound event was dropped because the current application is not responding "
1086 "and the user has started interacting with a different application";
1087 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 ALOGI("Dropped event because it is stale.");
1090 reason = "inbound event was dropped because it is stale";
1091 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001092 case DropReason::NO_POINTER_CAPTURE:
1093 ALOGI("Dropped event because there is no window with Pointer Capture.");
1094 reason = "inbound event was dropped because there is no window with Pointer Capture";
1095 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001096 case DropReason::NOT_DROPPED: {
1097 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 }
1101
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001103 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1105 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001108 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1110 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1112 synthesizeCancelationEventsForAllConnectionsLocked(options);
1113 } else {
1114 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1115 synthesizeCancelationEventsForAllConnectionsLocked(options);
1116 }
1117 break;
1118 }
Chris Yef59a2f42020-10-16 12:55:26 -07001119 case EventEntry::Type::SENSOR: {
1120 break;
1121 }
arthurhungb89ccb02020-12-30 16:19:01 +08001122 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1123 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001124 break;
1125 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001126 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001127 case EventEntry::Type::CONFIGURATION_CHANGED:
1128 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001129 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001130 break;
1131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 }
1133}
1134
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001135static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1137 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138}
1139
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001140bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1141 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1142 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1143 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144}
1145
1146bool InputDispatcher::isAppSwitchPendingLocked() {
1147 return mAppSwitchDueTime != LONG_LONG_MAX;
1148}
1149
1150void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1151 mAppSwitchDueTime = LONG_LONG_MAX;
1152
1153#if DEBUG_APP_SWITCH
1154 if (handled) {
1155 ALOGD("App switch has arrived.");
1156 } else {
1157 ALOGD("App switch was abandoned.");
1158 }
1159#endif
1160}
1161
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001163 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164}
1165
1166bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001167 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 return false;
1169 }
1170
1171 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001172 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001173 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001175 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176
1177 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001178 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 return true;
1180}
1181
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001182void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1183 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184}
1185
1186void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001187 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001189 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 releaseInboundEventLocked(entry);
1191 }
1192 traceInboundQueueLengthLocked();
1193}
1194
1195void InputDispatcher::releasePendingEventLocked() {
1196 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001198 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 }
1200}
1201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001204 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205#if DEBUG_DISPATCH_CYCLE
1206 ALOGD("Injected inbound event was dropped.");
1207#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001208 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 }
1210 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001211 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214}
1215
1216void InputDispatcher::resetKeyRepeatLocked() {
1217 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001218 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 }
1220}
1221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1223 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224
Michael Wright2e732952014-09-24 13:26:59 -07001225 uint32_t policyFlags = entry->policyFlags &
1226 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 std::shared_ptr<KeyEntry> newEntry =
1229 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1230 entry->source, entry->displayId, policyFlags, entry->action,
1231 entry->flags, entry->keyCode, entry->scanCode,
1232 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001234 newEntry->syntheticRepeat = true;
1235 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238}
1239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001240bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244#endif
1245
1246 // Reset key repeating in case a keyboard device was added or removed or something.
1247 resetKeyRepeatLocked();
1248
1249 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001250 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1251 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001253 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 return true;
1255}
1256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1258 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1261 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262#endif
1263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 synthesizeCancelationEventsForAllConnectionsLocked(options);
1267 return true;
1268}
1269
Vishnu Nairad321cd2020-08-20 16:40:21 -07001270void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001271 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001272 if (mPendingEvent != nullptr) {
1273 // Move the pending event to the front of the queue. This will give the chance
1274 // for the pending event to get dispatched to the newly focused window
1275 mInboundQueue.push_front(mPendingEvent);
1276 mPendingEvent = nullptr;
1277 }
1278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279 std::unique_ptr<FocusEntry> focusEntry =
1280 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1281 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001282
1283 // This event should go to the front of the queue, but behind all other focus events
1284 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001285 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001286 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 [](const std::shared_ptr<EventEntry>& event) {
1288 return event->type == EventEntry::Type::FOCUS;
1289 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001290
1291 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001293}
1294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001296 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001297 if (channel == nullptr) {
1298 return; // Window has gone away
1299 }
1300 InputTarget target;
1301 target.inputChannel = channel;
1302 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1303 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001304 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1305 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001306 std::string reason = std::string("reason=").append(entry->reason);
1307 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001308 dispatchEventLocked(currentTime, entry, {target});
1309}
1310
Prabir Pradhan99987712020-11-10 18:43:05 -08001311void InputDispatcher::dispatchPointerCaptureChangedLocked(
1312 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1313 DropReason& dropReason) {
1314 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001315 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1316 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1317 }
1318 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001319 // Pointer capture was already forcefully disabled because of focus change.
1320 dropReason = DropReason::NOT_DROPPED;
1321 return;
1322 }
1323
1324 // Set drop reason for early returns
1325 dropReason = DropReason::NO_POINTER_CAPTURE;
1326
1327 sp<IBinder> token;
1328 if (entry->pointerCaptureEnabled) {
1329 // Enable Pointer Capture
1330 if (!mFocusedWindowRequestedPointerCapture) {
1331 // This can happen if a window requests capture and immediately releases capture.
1332 ALOGW("No window requested Pointer Capture.");
1333 return;
1334 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001335 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001336 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1337 mWindowTokenWithPointerCapture = token;
1338 } else {
1339 // Disable Pointer Capture
1340 token = mWindowTokenWithPointerCapture;
1341 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001342 if (mFocusedWindowRequestedPointerCapture) {
1343 mFocusedWindowRequestedPointerCapture = false;
1344 setPointerCaptureLocked(false);
1345 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001346 }
1347
1348 auto channel = getInputChannelLocked(token);
1349 if (channel == nullptr) {
1350 // Window has gone away, clean up Pointer Capture state.
1351 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001352 if (mFocusedWindowRequestedPointerCapture) {
1353 mFocusedWindowRequestedPointerCapture = false;
1354 setPointerCaptureLocked(false);
1355 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001356 return;
1357 }
1358 InputTarget target;
1359 target.inputChannel = channel;
1360 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1361 entry->dispatchInProgress = true;
1362 dispatchEventLocked(currentTime, entry, {target});
1363
1364 dropReason = DropReason::NOT_DROPPED;
1365}
1366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 if (!entry->dispatchInProgress) {
1371 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1372 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1373 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1374 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001375 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 // We have seen two identical key downs in a row which indicates that the device
1377 // driver is automatically generating key repeats itself. We take note of the
1378 // repeat here, but we disable our own next key repeat timer since it is clear that
1379 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001380 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1381 // Make sure we don't get key down from a different device. If a different
1382 // device Id has same key pressed down, the new device Id will replace the
1383 // current one to hold the key repeat with repeat count reset.
1384 // In the future when got a KEY_UP on the device id, drop it and do not
1385 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1387 resetKeyRepeatLocked();
1388 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1389 } else {
1390 // Not a repeat. Save key down state in case we do see a repeat later.
1391 resetKeyRepeatLocked();
1392 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1393 }
1394 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001395 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1396 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001397 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001398#if DEBUG_INBOUND_EVENT_DETAILS
1399 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1400#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001401 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 resetKeyRepeatLocked();
1403 }
1404
1405 if (entry->repeatCount == 1) {
1406 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1407 } else {
1408 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1409 }
1410
1411 entry->dispatchInProgress = true;
1412
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001413 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415
1416 // Handle case where the policy asked us to try again later last time.
1417 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1418 if (currentTime < entry->interceptKeyWakeupTime) {
1419 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1420 *nextWakeupTime = entry->interceptKeyWakeupTime;
1421 }
1422 return false; // wait until next wakeup
1423 }
1424 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1425 entry->interceptKeyWakeupTime = 0;
1426 }
1427
1428 // Give the policy a chance to intercept the key.
1429 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1430 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001431 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001432 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001433 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001434 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001435 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001437 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 return false; // wait for the command to run
1439 } else {
1440 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1441 }
1442 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001443 if (*dropReason == DropReason::NOT_DROPPED) {
1444 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 }
1446 }
1447
1448 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001449 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001450 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001451 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1452 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001453 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 return true;
1455 }
1456
1457 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001458 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001459 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001460 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 return false;
1463 }
1464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 return true;
1468 }
1469
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001470 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001471 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472
1473 // Dispatch the key.
1474 dispatchEventLocked(currentTime, entry, inputTargets);
1475 return true;
1476}
1477
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001480 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001481 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1482 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001483 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1484 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1485 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486#endif
1487}
1488
Chris Yef59a2f42020-10-16 12:55:26 -07001489void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1490 mLock.unlock();
1491
1492 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1493 if (entry->accuracyChanged) {
1494 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1495 }
1496 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1497 entry->hwTimestamp, entry->values);
1498 mLock.lock();
1499}
1500
1501void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1502 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1503#if DEBUG_OUTBOUND_EVENT_DETAILS
1504 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1505 "source=0x%x, sensorType=%s",
1506 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001507 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001508#endif
1509 std::unique_ptr<CommandEntry> commandEntry =
1510 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1511 commandEntry->sensorEntry = entry;
1512 postCommandLocked(std::move(commandEntry));
1513}
1514
1515bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1516#if DEBUG_OUTBOUND_EVENT_DETAILS
1517 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1518 NamedEnum::string(sensorType).c_str());
1519#endif
1520 { // acquire lock
1521 std::scoped_lock _l(mLock);
1522
1523 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1524 std::shared_ptr<EventEntry> entry = *it;
1525 if (entry->type == EventEntry::Type::SENSOR) {
1526 it = mInboundQueue.erase(it);
1527 releaseInboundEventLocked(entry);
1528 }
1529 }
1530 }
1531 return true;
1532}
1533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001534bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001535 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001536 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001538 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 entry->dispatchInProgress = true;
1540
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001541 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 }
1543
1544 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001545 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001546 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1548 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 return true;
1550 }
1551
1552 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1553
1554 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001555 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556
1557 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001558 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 if (isPointerEvent) {
1560 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001562 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 } else {
1565 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001566 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return false;
1571 }
1572
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001575 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1576 return true;
1577 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001579 CancelationOptions::Mode mode(isPointerEvent
1580 ? CancelationOptions::CANCEL_POINTER_EVENTS
1581 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1582 CancelationOptions options(mode, "input event injection failed");
1583 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 return true;
1585 }
1586
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001587 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001588 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001590 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001591 std::unordered_map<int32_t, TouchState>::iterator it =
1592 mTouchStatesByDisplay.find(entry->displayId);
1593 if (it != mTouchStatesByDisplay.end()) {
1594 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001595 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001596 // The event has gone through these portal windows, so we add monitoring targets of
1597 // the corresponding displays as well.
1598 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05001599 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001600 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001601 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001602 }
1603 }
1604 }
1605 }
1606
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 // Dispatch the motion.
1608 if (conflictingPointerActions) {
1609 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 synthesizeCancelationEventsForAllConnectionsLocked(options);
1612 }
1613 dispatchEventLocked(currentTime, entry, inputTargets);
1614 return true;
1615}
1616
chaviw3277faf2021-05-19 16:45:23 -05001617void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001618 bool isExiting, const MotionEntry& motionEntry) {
1619 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1620 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1621 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1622 PointerCoords pointerCoords;
1623 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1624 pointerCoords.transform(windowHandle->getInfo()->transform);
1625
1626 std::unique_ptr<DragEntry> dragEntry =
1627 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1628 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1629 pointerCoords.getY());
1630
1631 enqueueInboundEventLocked(std::move(dragEntry));
1632}
1633
1634void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1635 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1636 if (channel == nullptr) {
1637 return; // Window has gone away
1638 }
1639 InputTarget target;
1640 target.inputChannel = channel;
1641 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1642 entry->dispatchInProgress = true;
1643 dispatchEventLocked(currentTime, entry, {target});
1644}
1645
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001646void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001648 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 ", policyFlags=0x%x, "
1650 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1651 "metaState=0x%x, buttonState=0x%x,"
1652 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1654 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1655 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001659 "x=%f, y=%f, pressure=%f, size=%f, "
1660 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1661 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001662 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1663 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1664 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1665 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1666 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1667 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1668 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1669 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1670 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1671 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 }
1673#endif
1674}
1675
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001676void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1677 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001678 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001679 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680#if DEBUG_DISPATCH_CYCLE
1681 ALOGD("dispatchEventToCurrentInputTargets");
1682#endif
1683
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001684 updateInteractionTokensLocked(*eventEntry, inputTargets);
1685
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1687
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001688 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001690 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001691 sp<Connection> connection =
1692 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001693 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001694 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001696 if (DEBUG_FOCUS) {
1697 ALOGD("Dropping event delivery to target with channel '%s' because it "
1698 "is no longer registered with the input dispatcher.",
1699 inputTarget.inputChannel->getName().c_str());
1700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702 }
1703}
1704
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001705void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1706 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1707 // If the policy decides to close the app, we will get a channel removal event via
1708 // unregisterInputChannel, and will clean up the connection that way. We are already not
1709 // sending new pointers to the connection when it blocked, but focused events will continue to
1710 // pile up.
1711 ALOGW("Canceling events for %s because it is unresponsive",
1712 connection->inputChannel->getName().c_str());
1713 if (connection->status == Connection::STATUS_NORMAL) {
1714 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1715 "application not responding");
1716 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718}
1719
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001720void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001721 if (DEBUG_FOCUS) {
1722 ALOGD("Resetting ANR timeouts.");
1723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724
1725 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001726 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001727 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728}
1729
Tiger Huang721e26f2018-07-24 22:26:19 +08001730/**
1731 * Get the display id that the given event should go to. If this event specifies a valid display id,
1732 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1733 * Focused display is the display that the user most recently interacted with.
1734 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001736 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001738 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001739 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1740 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 break;
1742 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001743 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001744 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1745 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001746 break;
1747 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001748 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001749 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001750 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001751 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001752 case EventEntry::Type::SENSOR:
1753 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001754 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001755 return ADISPLAY_ID_NONE;
1756 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001757 }
1758 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1759}
1760
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001761bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1762 const char* focusedWindowName) {
1763 if (mAnrTracker.empty()) {
1764 // already processed all events that we waited for
1765 mKeyIsWaitingForEventsTimeout = std::nullopt;
1766 return false;
1767 }
1768
1769 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1770 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001771 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001772 mKeyIsWaitingForEventsTimeout = currentTime +
1773 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1774 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001775 return true;
1776 }
1777
1778 // We still have pending events, and already started the timer
1779 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1780 return true; // Still waiting
1781 }
1782
1783 // Waited too long, and some connection still hasn't processed all motions
1784 // Just send the key to the focused window
1785 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1786 focusedWindowName);
1787 mKeyIsWaitingForEventsTimeout = std::nullopt;
1788 return false;
1789}
1790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001791InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1792 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1793 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001794 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795
Tiger Huang721e26f2018-07-24 22:26:19 +08001796 int32_t displayId = getTargetDisplayId(entry);
chaviw3277faf2021-05-19 16:45:23 -05001797 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001798 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001799 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1800
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 // If there is no currently focused window and no focused application
1802 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001803 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1804 ALOGI("Dropping %s event because there is no focused window or focused application in "
1805 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001806 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001807 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 }
1809
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001810 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1811 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1812 // start interacting with another application via touch (app switch). This code can be removed
1813 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1814 // an app is expected to have a focused window.
1815 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1816 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1817 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001818 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1819 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1820 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001821 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001822 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 ALOGW("Waiting because no window has focus but %s may eventually add a "
1824 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001825 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001826 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001827 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001828 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1829 // Already raised ANR. Drop the event
1830 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001831 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833 } else {
1834 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 }
1837 }
1838
1839 // we have a valid, non-null focused window
1840 resetNoFocusedWindowTimeoutLocked();
1841
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001843 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 }
1846
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001847 if (focusedWindowHandle->getInfo()->paused) {
1848 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001849 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001850 }
1851
1852 // If the event is a key event, then we must wait for all previous events to
1853 // complete before delivering it because previous events may have the
1854 // side-effect of transferring focus to a different window and we want to
1855 // ensure that the following keys are sent to the new window.
1856 //
1857 // Suppose the user touches a button in a window then immediately presses "A".
1858 // If the button causes a pop-up window to appear then we want to ensure that
1859 // the "A" key is delivered to the new pop-up window. This is because users
1860 // often anticipate pending UI changes when typing on a keyboard.
1861 // To obtain this behavior, we must serialize key events with respect to all
1862 // prior input events.
1863 if (entry.type == EventEntry::Type::KEY) {
1864 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1865 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001866 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
1869
1870 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001871 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1873 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874
1875 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877}
1878
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879/**
1880 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1881 * that are currently unresponsive.
1882 */
1883std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1884 const std::vector<TouchedMonitor>& monitors) const {
1885 std::vector<TouchedMonitor> responsiveMonitors;
1886 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1887 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1888 sp<Connection> connection = getConnectionLocked(
1889 monitor.monitor.inputChannel->getConnectionToken());
1890 if (connection == nullptr) {
1891 ALOGE("Could not find connection for monitor %s",
1892 monitor.monitor.inputChannel->getName().c_str());
1893 return false;
1894 }
1895 if (!connection->responsive) {
1896 ALOGW("Unresponsive monitor %s will not get the new gesture",
1897 connection->inputChannel->getName().c_str());
1898 return false;
1899 }
1900 return true;
1901 });
1902 return responsiveMonitors;
1903}
1904
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001905InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1906 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1907 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001908 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 enum InjectionPermission {
1910 INJECTION_PERMISSION_UNKNOWN,
1911 INJECTION_PERMISSION_GRANTED,
1912 INJECTION_PERMISSION_DENIED
1913 };
1914
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 // For security reasons, we defer updating the touch state until we are sure that
1916 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001917 int32_t displayId = entry.displayId;
1918 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1920
1921 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001922 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw3277faf2021-05-19 16:45:23 -05001924 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1925 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001927 // Copy current touch state into tempTouchState.
1928 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1929 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001930 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001931 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001932 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1933 mTouchStatesByDisplay.find(displayId);
1934 if (oldStateIt != mTouchStatesByDisplay.end()) {
1935 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001936 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001937 }
1938
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 bool isSplit = tempTouchState.split;
1940 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1941 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1942 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1944 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1945 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1946 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1947 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001948 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 bool wrongDevice = false;
1950 if (newGesture) {
1951 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001953 ALOGI("Dropping event because a pointer for a different device is already down "
1954 "in display %" PRId32,
1955 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001956 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001957 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958 switchedDevice = false;
1959 wrongDevice = true;
1960 goto Failed;
1961 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001962 tempTouchState.reset();
1963 tempTouchState.down = down;
1964 tempTouchState.deviceId = entry.deviceId;
1965 tempTouchState.source = entry.source;
1966 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001968 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001969 ALOGI("Dropping move event because a pointer for a different device is already active "
1970 "in display %" PRId32,
1971 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001972 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001973 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001974 switchedDevice = false;
1975 wrongDevice = true;
1976 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
1978
1979 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1980 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1981
Garfield Tan00f511d2019-06-12 16:55:40 -07001982 int32_t x;
1983 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001985 // Always dispatch mouse events to cursor position.
1986 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987 x = int32_t(entry.xCursorPosition);
1988 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001989 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001990 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1991 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001992 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001993 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001994 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001995 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1996 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001997
1998 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002003 if (newTouchedWindowHandle != nullptr &&
2004 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002005 // New window supports splitting, but we should never split mouse events.
2006 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 } else if (isSplit) {
2008 // New window does not support splitting but we have already split events.
2009 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002010 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 }
2012
2013 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002014 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002016 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002017 }
2018
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002019 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2020 ALOGI("Not sending touch event to %s because it is paused",
2021 newTouchedWindowHandle->getName().c_str());
2022 newTouchedWindowHandle = nullptr;
2023 }
2024
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002025 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002027 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2028 if (!isResponsive) {
2029 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002030 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2031 newTouchedWindowHandle = nullptr;
2032 }
2033 }
2034
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002035 // Drop events that can't be trusted due to occlusion
2036 if (newTouchedWindowHandle != nullptr &&
2037 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2038 TouchOcclusionInfo occlusionInfo =
2039 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002040 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002041 if (DEBUG_TOUCH_OCCLUSION) {
2042 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2043 for (const auto& log : occlusionInfo.debugInfo) {
2044 ALOGD("%s", log.c_str());
2045 }
2046 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002047 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2048 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2049 ALOGW("Dropping untrusted touch event due to %s/%d",
2050 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2051 newTouchedWindowHandle = nullptr;
2052 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002053 }
2054 }
2055
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002056 // Also don't send the new touch event to unresponsive gesture monitors
2057 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2058
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2060 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002061 "(%d, %d) in display %" PRId32 ".",
2062 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002063 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002064 goto Failed;
2065 }
2066
2067 if (newTouchedWindowHandle != nullptr) {
2068 // Set target flags.
2069 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2070 if (isSplit) {
2071 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002073 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2074 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2075 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2076 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2077 }
2078
2079 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002080 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2081 newHoverWindowHandle = nullptr;
2082 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002083 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002084 }
2085
2086 // Update the temporary touch state.
2087 BitSet32 pointerIds;
2088 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002089 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002090 pointerIds.markBit(pointerId);
2091 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002092 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 }
2094
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 } else {
2097 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2098
2099 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002101 if (DEBUG_FOCUS) {
2102 ALOGD("Dropping event because the pointer is not down or we previously "
2103 "dropped the pointer down event in display %" PRId32,
2104 displayId);
2105 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002106 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 goto Failed;
2108 }
2109
arthurhung6d4bed92021-03-17 11:59:33 +08002110 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002111
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002113 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002114 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002115 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2116 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117
chaviw3277faf2021-05-19 16:45:23 -05002118 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002119 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002120 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2122 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002123 if (DEBUG_FOCUS) {
2124 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2125 oldTouchedWindowHandle->getName().c_str(),
2126 newTouchedWindowHandle->getName().c_str(), displayId);
2127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002129 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2130 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2131 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132
2133 // Make a slippery entrance into the new window.
2134 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2135 isSplit = true;
2136 }
2137
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002138 int32_t targetFlags =
2139 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 if (isSplit) {
2141 targetFlags |= InputTarget::FLAG_SPLIT;
2142 }
2143 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2144 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002145 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2146 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 }
2148
2149 BitSet32 pointerIds;
2150 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002151 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155 }
2156 }
2157
2158 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002159 // Let the previous window know that the hover sequence is over, unless we already did it
2160 // when dispatching it as is to newTouchedWindowHandle.
2161 if (mLastHoverWindowHandle != nullptr &&
2162 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2163 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164#if DEBUG_HOVER
2165 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002166 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002168 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2169 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171
Garfield Tandf26e862020-07-01 20:18:19 -07002172 // Let the new window know that the hover sequence is starting, unless we already did it
2173 // when dispatching it as is to newTouchedWindowHandle.
2174 if (newHoverWindowHandle != nullptr &&
2175 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2176 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177#if DEBUG_HOVER
2178 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002181 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2182 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2183 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
2185 }
2186
2187 // Check permission to inject into all touched foreground windows and ensure there
2188 // is at least one touched foreground window.
2189 {
2190 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002191 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2193 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002194 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002195 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 injectionPermission = INJECTION_PERMISSION_DENIED;
2197 goto Failed;
2198 }
2199 }
2200 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002201 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002202 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002203 ALOGI("Dropping event because there is no touched foreground window in display "
2204 "%" PRId32 " or gesture monitor to receive it.",
2205 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002206 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 goto Failed;
2208 }
2209
2210 // Permission granted to injection into all touched foreground windows.
2211 injectionPermission = INJECTION_PERMISSION_GRANTED;
2212 }
2213
2214 // Check whether windows listening for outside touches are owned by the same UID. If it is
2215 // set the policy flag that we will not reveal coordinate information to this window.
2216 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002217 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002219 if (foregroundWindowHandle) {
2220 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002221 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw3277faf2021-05-19 16:45:23 -05002223 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2224 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2225 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002226 InputTarget::FLAG_ZERO_COORDS,
2227 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230 }
2231 }
2232 }
2233
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 // If this is the first pointer going down and the touched window has a wallpaper
2235 // then also add the touched wallpaper windows so they are locked in for the duration
2236 // of the touch gesture.
2237 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2238 // engine only supports touch events. We would need to add a mechanism similar
2239 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2240 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002241 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002243 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw3277faf2021-05-19 16:45:23 -05002244 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002245 getWindowHandlesLocked(displayId);
chaviw3277faf2021-05-19 16:45:23 -05002246 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2247 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 if (info->displayId == displayId &&
chaviw3277faf2021-05-19 16:45:23 -05002249 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002251 .addOrUpdateWindow(windowHandle,
2252 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2253 InputTarget::
2254 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2255 InputTarget::FLAG_DISPATCH_AS_IS,
2256 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
2258 }
2259 }
2260 }
2261
2262 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002263 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002265 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002270 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002271 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002273 }
2274
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 // Drop the outside or hover touch windows since we will not care about them
2276 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002277 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278
2279Failed:
2280 // Check injection permission once and for all.
2281 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002282 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 injectionPermission = INJECTION_PERMISSION_GRANTED;
2284 } else {
2285 injectionPermission = INJECTION_PERMISSION_DENIED;
2286 }
2287 }
2288
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002289 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2290 return injectionResult;
2291 }
2292
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002294 if (!wrongDevice) {
2295 if (switchedDevice) {
2296 if (DEBUG_FOCUS) {
2297 ALOGD("Conflicting pointer actions: Switched to a different device.");
2298 }
2299 *outConflictingPointerActions = true;
2300 }
2301
2302 if (isHoverAction) {
2303 // Started hovering, therefore no longer down.
2304 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002305 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002306 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2307 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 *outConflictingPointerActions = true;
2310 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002311 tempTouchState.reset();
2312 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2313 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2314 tempTouchState.deviceId = entry.deviceId;
2315 tempTouchState.source = entry.source;
2316 tempTouchState.displayId = displayId;
2317 }
2318 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2319 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2320 // All pointers up or canceled.
2321 tempTouchState.reset();
2322 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2323 // First pointer went down.
2324 if (oldState && oldState->down) {
2325 if (DEBUG_FOCUS) {
2326 ALOGD("Conflicting pointer actions: Down received while already down.");
2327 }
2328 *outConflictingPointerActions = true;
2329 }
2330 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2331 // One pointer went up.
2332 if (isSplit) {
2333 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2334 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002336 for (size_t i = 0; i < tempTouchState.windows.size();) {
2337 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2338 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2339 touchedWindow.pointerIds.clearBit(pointerId);
2340 if (touchedWindow.pointerIds.isEmpty()) {
2341 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2342 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002345 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002347 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002348 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002349
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002350 // Save changes unless the action was scroll in which case the temporary touch
2351 // state was only valid for this one action.
2352 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2353 if (tempTouchState.displayId >= 0) {
2354 mTouchStatesByDisplay[displayId] = tempTouchState;
2355 } else {
2356 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002360 // Update hover state.
2361 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 }
2363
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 return injectionResult;
2365}
2366
arthurhung6d4bed92021-03-17 11:59:33 +08002367void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw3277faf2021-05-19 16:45:23 -05002368 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002369 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2370 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2371 true /*ignoreDragWindow*/);
2372 if (dropWindow) {
2373 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2374 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002375 } else {
2376 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002377 }
2378 mDragState.reset();
2379}
2380
2381void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2382 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002383 return;
2384 }
2385
arthurhung6d4bed92021-03-17 11:59:33 +08002386 if (!mDragState->isStartDrag) {
2387 mDragState->isStartDrag = true;
2388 mDragState->isStylusButtonDownAtStart =
2389 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2390 }
2391
arthurhungb89ccb02020-12-30 16:19:01 +08002392 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2393 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2394 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2395 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002396 // Handle the special case : stylus button no longer pressed.
2397 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2398 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2399 finishDragAndDrop(entry.displayId, x, y);
2400 return;
2401 }
2402
chaviw3277faf2021-05-19 16:45:23 -05002403 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002404 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002405 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2406 true /*ignoreDragWindow*/);
2407 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002408 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2409 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2410 if (mDragState->dragHoverWindowHandle != nullptr) {
2411 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2412 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002413 }
arthurhung6d4bed92021-03-17 11:59:33 +08002414 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002415 }
2416 // enqueue drag location if needed.
2417 if (hoverWindowHandle != nullptr) {
2418 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2419 }
arthurhung6d4bed92021-03-17 11:59:33 +08002420 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2421 finishDragAndDrop(entry.displayId, x, y);
2422 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002423 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002424 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002425 }
2426}
2427
chaviw3277faf2021-05-19 16:45:23 -05002428void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 int32_t targetFlags, BitSet32 pointerIds,
2430 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002431 std::vector<InputTarget>::iterator it =
2432 std::find_if(inputTargets.begin(), inputTargets.end(),
2433 [&windowHandle](const InputTarget& inputTarget) {
2434 return inputTarget.inputChannel->getConnectionToken() ==
2435 windowHandle->getToken();
2436 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002437
chaviw3277faf2021-05-19 16:45:23 -05002438 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439
2440 if (it == inputTargets.end()) {
2441 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002442 std::shared_ptr<InputChannel> inputChannel =
2443 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002444 if (inputChannel == nullptr) {
2445 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2446 return;
2447 }
2448 inputTarget.inputChannel = inputChannel;
2449 inputTarget.flags = targetFlags;
2450 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002451 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002452 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002453 inputTargets.push_back(inputTarget);
2454 it = inputTargets.end() - 1;
2455 }
2456
2457 ALOG_ASSERT(it->flags == targetFlags);
2458 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2459
chaviw1ff3d1e2020-07-01 15:53:47 -07002460 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461}
2462
Michael Wright3dd60e22019-03-27 22:06:44 +00002463void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002464 int32_t displayId, float xOffset,
2465 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002466 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2467 mGlobalMonitorsByDisplay.find(displayId);
2468
2469 if (it != mGlobalMonitorsByDisplay.end()) {
2470 const std::vector<Monitor>& monitors = it->second;
2471 for (const Monitor& monitor : monitors) {
2472 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 }
2475}
2476
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002477void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2478 float yOffset,
2479 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002480 InputTarget target;
2481 target.inputChannel = monitor.inputChannel;
2482 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002483 ui::Transform t;
2484 t.set(xOffset, yOffset);
2485 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002486 inputTargets.push_back(target);
2487}
2488
chaviw3277faf2021-05-19 16:45:23 -05002489bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490 const InjectionState* injectionState) {
2491 if (injectionState &&
2492 (windowHandle == nullptr ||
2493 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2494 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002495 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497 "owned by uid %d",
2498 injectionState->injectorPid, injectionState->injectorUid,
2499 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 } else {
2501 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 }
2504 return false;
2505 }
2506 return true;
2507}
2508
Robert Carrc9bf1d32020-04-13 17:21:08 -07002509/**
2510 * Indicate whether one window handle should be considered as obscuring
2511 * another window handle. We only check a few preconditions. Actually
2512 * checking the bounds is left to the caller.
2513 */
chaviw3277faf2021-05-19 16:45:23 -05002514static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2515 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002516 // Compare by token so cloned layers aren't counted
2517 if (haveSameToken(windowHandle, otherHandle)) {
2518 return false;
2519 }
2520 auto info = windowHandle->getInfo();
2521 auto otherInfo = otherHandle->getInfo();
2522 if (!otherInfo->visible) {
2523 return false;
chaviw3277faf2021-05-19 16:45:23 -05002524 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002525 // Those act as if they were invisible, so we don't need to flag them.
2526 // We do want to potentially flag touchable windows even if they have 0
2527 // opacity, since they can consume touches and alter the effects of the
2528 // user interaction (eg. apps that rely on
2529 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2530 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2531 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002532 } else if (info->ownerUid == otherInfo->ownerUid) {
2533 // If ownerUid is the same we don't generate occlusion events as there
2534 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002535 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002536 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002537 return false;
2538 } else if (otherInfo->displayId != info->displayId) {
2539 return false;
2540 }
2541 return true;
2542}
2543
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002544/**
2545 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2546 * untrusted, one should check:
2547 *
2548 * 1. If result.hasBlockingOcclusion is true.
2549 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2550 * BLOCK_UNTRUSTED.
2551 *
2552 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2553 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2554 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2555 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2556 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2557 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2558 *
2559 * If neither of those is true, then it means the touch can be allowed.
2560 */
2561InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw3277faf2021-05-19 16:45:23 -05002562 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2563 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002564 int32_t displayId = windowInfo->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002565 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002566 TouchOcclusionInfo info;
2567 info.hasBlockingOcclusion = false;
2568 info.obscuringOpacity = 0;
2569 info.obscuringUid = -1;
2570 std::map<int32_t, float> opacityByUid;
chaviw3277faf2021-05-19 16:45:23 -05002571 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002572 if (windowHandle == otherHandle) {
2573 break; // All future windows are below us. Exit early.
2574 }
chaviw3277faf2021-05-19 16:45:23 -05002575 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002576 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2577 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002578 if (DEBUG_TOUCH_OCCLUSION) {
2579 info.debugInfo.push_back(
2580 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2581 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002582 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2583 // we perform the checks below to see if the touch can be propagated or not based on the
2584 // window's touch occlusion mode
2585 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2586 info.hasBlockingOcclusion = true;
2587 info.obscuringUid = otherInfo->ownerUid;
2588 info.obscuringPackage = otherInfo->packageName;
2589 break;
2590 }
2591 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2592 uint32_t uid = otherInfo->ownerUid;
2593 float opacity =
2594 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2595 // Given windows A and B:
2596 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2597 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2598 opacityByUid[uid] = opacity;
2599 if (opacity > info.obscuringOpacity) {
2600 info.obscuringOpacity = opacity;
2601 info.obscuringUid = uid;
2602 info.obscuringPackage = otherInfo->packageName;
2603 }
2604 }
2605 }
2606 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002607 if (DEBUG_TOUCH_OCCLUSION) {
2608 info.debugInfo.push_back(
2609 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2610 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002611 return info;
2612}
2613
chaviw3277faf2021-05-19 16:45:23 -05002614std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002615 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002616 return StringPrintf(INDENT2
2617 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2618 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2619 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2620 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002621 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002622 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002623 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002624 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2625 info->frameTop, info->frameRight, info->frameBottom,
2626 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002627 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2628 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2629 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002630}
2631
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002632bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2633 if (occlusionInfo.hasBlockingOcclusion) {
2634 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2635 occlusionInfo.obscuringUid);
2636 return false;
2637 }
2638 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2639 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2640 "%.2f, maximum allowed = %.2f)",
2641 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2642 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2643 return false;
2644 }
2645 return true;
2646}
2647
chaviw3277faf2021-05-19 16:45:23 -05002648bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002649 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002651 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2652 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002653 if (windowHandle == otherHandle) {
2654 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
chaviw3277faf2021-05-19 16:45:23 -05002656 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002657 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002658 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 return true;
2660 }
2661 }
2662 return false;
2663}
2664
chaviw3277faf2021-05-19 16:45:23 -05002665bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002666 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002667 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2668 const WindowInfo* windowInfo = windowHandle->getInfo();
2669 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002670 if (windowHandle == otherHandle) {
2671 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002672 }
chaviw3277faf2021-05-19 16:45:23 -05002673 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002674 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002675 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002676 return true;
2677 }
2678 }
2679 return false;
2680}
2681
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002682std::string InputDispatcher::getApplicationWindowLabel(
chaviw3277faf2021-05-19 16:45:23 -05002683 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002684 if (applicationHandle != nullptr) {
2685 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002686 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 } else {
2688 return applicationHandle->getName();
2689 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002690 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002691 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002693 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 }
2695}
2696
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002697void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002698 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002699 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2700 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002701 // Focus or pointer capture changed events are passed to apps, but do not represent user
2702 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002703 return;
2704 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002705 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw3277faf2021-05-19 16:45:23 -05002706 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002707 if (focusedWindowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05002708 const WindowInfo* info = focusedWindowHandle->getInfo();
2709 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002711 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712#endif
2713 return;
2714 }
2715 }
2716
2717 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002718 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002719 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002720 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2721 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 return;
2723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002725 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 eventType = USER_ACTIVITY_EVENT_TOUCH;
2727 }
2728 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002730 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002731 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2732 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 return;
2734 }
2735 eventType = USER_ACTIVITY_EVENT_BUTTON;
2736 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002738 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002739 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002740 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002741 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002742 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2743 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002744 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002745 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002746 break;
2747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 }
2749
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002750 std::unique_ptr<CommandEntry> commandEntry =
2751 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002752 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002754 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002755 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756}
2757
2758void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002760 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002761 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002762 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002764 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002765 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002766 ATRACE_NAME(message.c_str());
2767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768#if DEBUG_DISPATCH_CYCLE
2769 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002770 "globalScaleFactor=%f, pointerIds=0x%x %s",
2771 connection->getInputChannelName().c_str(), inputTarget.flags,
2772 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2773 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774#endif
2775
2776 // Skip this event if the connection status is not normal.
2777 // We don't want to enqueue additional outbound events if the connection is broken.
2778 if (connection->status != Connection::STATUS_NORMAL) {
2779#if DEBUG_DISPATCH_CYCLE
2780 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782#endif
2783 return;
2784 }
2785
2786 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002787 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2788 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2789 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002790 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002792 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002793 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002794 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002795 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 if (!splitMotionEntry) {
2797 return; // split event was dropped
2798 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002799 if (DEBUG_FOCUS) {
2800 ALOGD("channel '%s' ~ Split motion event.",
2801 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002802 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002803 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002804 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2805 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 return;
2807 }
2808 }
2809
2810 // Not splitting. Enqueue dispatch entries for the event as is.
2811 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2812}
2813
2814void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002815 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002816 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002817 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002818 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002819 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002820 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002821 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002822 ATRACE_NAME(message.c_str());
2823 }
2824
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002825 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826
2827 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002828 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002830 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002831 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002832 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002834 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002836 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840
2841 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002842 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 startDispatchCycleLocked(currentTime, connection);
2844 }
2845}
2846
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002848 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002849 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002850 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002851 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002852 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2853 connection->getInputChannelName().c_str(),
2854 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002855 ATRACE_NAME(message.c_str());
2856 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002857 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 if (!(inputTargetFlags & dispatchMode)) {
2859 return;
2860 }
2861 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2862
2863 // This is a new event.
2864 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002865 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002866 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002868 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2869 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002870 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002872 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002873 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002874 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002875 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002876 dispatchEntry->resolvedAction = keyEntry.action;
2877 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2880 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2883 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 return; // skip the inconsistent event
2886 }
2887 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002890 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002891 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002892 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2893 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2894 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2895 static_cast<int32_t>(IdGenerator::Source::OTHER);
2896 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2898 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2899 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2900 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2901 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2902 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2903 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2904 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2905 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2906 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2907 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002908 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002909 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 }
2911 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2913 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2916 "event",
2917 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002919 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2920 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002924 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2926 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2927 }
2928 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2929 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2933 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2936 "event",
2937 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 return; // skip the inconsistent event
2940 }
2941
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002942 dispatchEntry->resolvedEventId =
2943 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2944 ? mIdGenerator.nextId()
2945 : motionEntry.id;
2946 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2947 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2948 ") to MotionEvent(id=0x%" PRIx32 ").",
2949 motionEntry.id, dispatchEntry->resolvedEventId);
2950 ATRACE_NAME(message.c_str());
2951 }
2952
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002953 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2954 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2955 // Skip reporting pointer down outside focus to the policy.
2956 break;
2957 }
2958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002960 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961
2962 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002964 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002965 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2966 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002967 break;
2968 }
Chris Yef59a2f42020-10-16 12:55:26 -07002969 case EventEntry::Type::SENSOR: {
2970 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2971 break;
2972 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002973 case EventEntry::Type::CONFIGURATION_CHANGED:
2974 case EventEntry::Type::DEVICE_RESET: {
2975 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002976 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002977 break;
2978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 }
2980
2981 // Remember that we are waiting for this dispatch to complete.
2982 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002983 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 }
2985
2986 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002987 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002988 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002989}
2990
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002991/**
2992 * This function is purely for debugging. It helps us understand where the user interaction
2993 * was taking place. For example, if user is touching launcher, we will see a log that user
2994 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2995 * We will see both launcher and wallpaper in that list.
2996 * Once the interaction with a particular set of connections starts, no new logs will be printed
2997 * until the set of interacted connections changes.
2998 *
2999 * The following items are skipped, to reduce the logspam:
3000 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3001 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3002 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3003 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3004 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003005 */
3006void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3007 const std::vector<InputTarget>& targets) {
3008 // Skip ACTION_UP events, and all events other than keys and motions
3009 if (entry.type == EventEntry::Type::KEY) {
3010 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3011 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3012 return;
3013 }
3014 } else if (entry.type == EventEntry::Type::MOTION) {
3015 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3016 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3017 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3018 return;
3019 }
3020 } else {
3021 return; // Not a key or a motion
3022 }
3023
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003024 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003025 std::vector<sp<Connection>> newConnections;
3026 for (const InputTarget& target : targets) {
3027 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3028 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3029 continue; // Skip windows that receive ACTION_OUTSIDE
3030 }
3031
3032 sp<IBinder> token = target.inputChannel->getConnectionToken();
3033 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003034 if (connection == nullptr) {
3035 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003036 }
3037 newConnectionTokens.insert(std::move(token));
3038 newConnections.emplace_back(connection);
3039 }
3040 if (newConnectionTokens == mInteractionConnectionTokens) {
3041 return; // no change
3042 }
3043 mInteractionConnectionTokens = newConnectionTokens;
3044
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003045 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003046 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003047 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003048 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003049 std::string message = "Interaction with: " + targetList;
3050 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003051 message += "<none>";
3052 }
3053 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3054}
3055
chaviwfd6d3512019-03-25 13:23:49 -07003056void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003057 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003058 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003059 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3060 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003061 return;
3062 }
3063
Vishnu Nairc519ff72021-01-21 08:23:08 -08003064 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003065 if (focusedToken == token) {
3066 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003067 return;
3068 }
3069
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003070 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3071 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003072 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003073 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074}
3075
3076void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003078 if (ATRACE_ENABLED()) {
3079 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003081 ATRACE_NAME(message.c_str());
3082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085#endif
3086
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003087 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3088 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003090 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003091 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003092 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093
3094 // Publish the event.
3095 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003096 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3097 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003098 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003099 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3100 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003103 status = connection->inputPublisher
3104 .publishKeyEvent(dispatchEntry->seq,
3105 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3106 keyEntry.source, keyEntry.displayId,
3107 std::move(hmac), dispatchEntry->resolvedAction,
3108 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3109 keyEntry.scanCode, keyEntry.metaState,
3110 keyEntry.repeatCount, keyEntry.downTime,
3111 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
3114
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003115 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003116 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003118 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003119 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120
chaviw82357092020-01-28 13:13:06 -08003121 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003122 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003123 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3124 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003125 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3127 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003128 // Don't apply window scale here since we don't want scale to affect raw
3129 // coordinates. The scale will be sent back to the client and applied
3130 // later when requesting relative coordinates.
3131 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3132 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 }
3134 usingCoords = scaledCoords;
3135 }
3136 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 // We don't want the dispatch target to know.
3138 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003139 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 scaledCoords[i].clear();
3141 }
3142 usingCoords = scaledCoords;
3143 }
3144 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003145
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003146 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003147
3148 // Publish the motion event.
3149 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003150 .publishMotionEvent(dispatchEntry->seq,
3151 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003152 motionEntry.deviceId, motionEntry.source,
3153 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003154 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003155 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003157 motionEntry.edgeFlags, motionEntry.metaState,
3158 motionEntry.buttonState,
3159 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003160 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 motionEntry.xPrecision, motionEntry.yPrecision,
3162 motionEntry.xCursorPosition,
3163 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003164 dispatchEntry->displaySize.x,
3165 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003166 motionEntry.downTime, motionEntry.eventTime,
3167 motionEntry.pointerCount,
3168 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 break;
3170 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003171
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003172 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003173 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003174 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003175 focusEntry.id,
3176 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003177 mInTouchMode);
3178 break;
3179 }
3180
Prabir Pradhan99987712020-11-10 18:43:05 -08003181 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3182 const auto& captureEntry =
3183 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3184 status = connection->inputPublisher
3185 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3186 captureEntry.pointerCaptureEnabled);
3187 break;
3188 }
3189
arthurhungb89ccb02020-12-30 16:19:01 +08003190 case EventEntry::Type::DRAG: {
3191 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3192 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3193 dragEntry.id, dragEntry.x,
3194 dragEntry.y,
3195 dragEntry.isExiting);
3196 break;
3197 }
3198
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003199 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003200 case EventEntry::Type::DEVICE_RESET:
3201 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003202 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003203 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
3207
3208 // Check the result.
3209 if (status) {
3210 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003211 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213 "This is unexpected because the wait queue is empty, so the pipe "
3214 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003215 "event to it, status=%s(%d)",
3216 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3217 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3219 } else {
3220 // Pipe is full and we are waiting for the app to finish process some events
3221 // before sending more events to it.
3222#if DEBUG_DISPATCH_CYCLE
3223 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 "waiting for the application to catch up",
3225 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
3228 } else {
3229 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003230 "status=%s(%d)",
3231 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3232 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3234 }
3235 return;
3236 }
3237
3238 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003239 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3240 connection->outboundQueue.end(),
3241 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003242 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003243 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003244 if (connection->responsive) {
3245 mAnrTracker.insert(dispatchEntry->timeoutTime,
3246 connection->inputChannel->getConnectionToken());
3247 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003248 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250}
3251
chaviw09c8d2d2020-08-24 15:48:26 -07003252std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3253 size_t size;
3254 switch (event.type) {
3255 case VerifiedInputEvent::Type::KEY: {
3256 size = sizeof(VerifiedKeyEvent);
3257 break;
3258 }
3259 case VerifiedInputEvent::Type::MOTION: {
3260 size = sizeof(VerifiedMotionEvent);
3261 break;
3262 }
3263 }
3264 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3265 return mHmacKeyManager.sign(start, size);
3266}
3267
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003268const std::array<uint8_t, 32> InputDispatcher::getSignature(
3269 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3270 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3271 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3272 // Only sign events up and down events as the purely move events
3273 // are tied to their up/down counterparts so signing would be redundant.
3274 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3275 verifiedEvent.actionMasked = actionMasked;
3276 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003277 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003278 }
3279 return INVALID_HMAC;
3280}
3281
3282const std::array<uint8_t, 32> InputDispatcher::getSignature(
3283 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3284 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3285 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3286 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003287 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003288}
3289
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003291 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003292 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293#if DEBUG_DISPATCH_CYCLE
3294 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296#endif
3297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 if (connection->status == Connection::STATUS_BROKEN ||
3299 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 return;
3301 }
3302
3303 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003304 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305}
3306
3307void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 const sp<Connection>& connection,
3309 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310#if DEBUG_DISPATCH_CYCLE
3311 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313#endif
3314
3315 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003316 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003317 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003318 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003319 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320
3321 // The connection appears to be unrecoverably broken.
3322 // Ignore already broken or zombie connections.
3323 if (connection->status == Connection::STATUS_NORMAL) {
3324 connection->status = Connection::STATUS_BROKEN;
3325
3326 if (notify) {
3327 // Notify other system components.
3328 onDispatchCycleBrokenLocked(currentTime, connection);
3329 }
3330 }
3331}
3332
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003333void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3334 while (!queue.empty()) {
3335 DispatchEntry* dispatchEntry = queue.front();
3336 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003337 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 }
3339}
3340
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003341void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003343 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 }
3345 delete dispatchEntry;
3346}
3347
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003348int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3349 std::scoped_lock _l(mLock);
3350 sp<Connection> connection = getConnectionLocked(connectionToken);
3351 if (connection == nullptr) {
3352 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3353 connectionToken.get(), events);
3354 return 0; // remove the callback
3355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003357 bool notify;
3358 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3359 if (!(events & ALOOPER_EVENT_INPUT)) {
3360 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3361 "events=0x%x",
3362 connection->getInputChannelName().c_str(), events);
3363 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 }
3365
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003366 nsecs_t currentTime = now();
3367 bool gotOne = false;
3368 status_t status = OK;
3369 for (;;) {
3370 Result<InputPublisher::ConsumerResponse> result =
3371 connection->inputPublisher.receiveConsumerResponse();
3372 if (!result.ok()) {
3373 status = result.error().code();
3374 break;
3375 }
3376
3377 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3378 const InputPublisher::Finished& finish =
3379 std::get<InputPublisher::Finished>(*result);
3380 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3381 finish.consumeTime);
3382 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003383 if (shouldReportMetricsForConnection(*connection)) {
3384 const InputPublisher::Timeline& timeline =
3385 std::get<InputPublisher::Timeline>(*result);
3386 mLatencyTracker
3387 .trackGraphicsLatency(timeline.inputEventId,
3388 connection->inputChannel->getConnectionToken(),
3389 std::move(timeline.graphicsTimeline));
3390 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003391 }
3392 gotOne = true;
3393 }
3394 if (gotOne) {
3395 runCommandsLockedInterruptible();
3396 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 return 1;
3398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003401 notify = status != DEAD_OBJECT || !connection->monitor;
3402 if (notify) {
3403 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3404 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3405 status);
3406 }
3407 } else {
3408 // Monitor channels are never explicitly unregistered.
3409 // We do it automatically when the remote endpoint is closed so don't warn about them.
3410 const bool stillHaveWindowHandle =
3411 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3412 notify = !connection->monitor && stillHaveWindowHandle;
3413 if (notify) {
3414 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3415 connection->getInputChannelName().c_str(), events);
3416 }
3417 }
3418
3419 // Remove the channel.
3420 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3421 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422}
3423
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003424void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003426 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003427 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 }
3429}
3430
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003432 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003433 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3434 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3435}
3436
3437void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3438 const CancelationOptions& options,
3439 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3440 for (const auto& it : monitorsByDisplay) {
3441 const std::vector<Monitor>& monitors = it.second;
3442 for (const Monitor& monitor : monitors) {
3443 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003444 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003445 }
3446}
3447
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003449 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003450 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003451 if (connection == nullptr) {
3452 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003454
3455 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456}
3457
3458void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3459 const sp<Connection>& connection, const CancelationOptions& options) {
3460 if (connection->status == Connection::STATUS_BROKEN) {
3461 return;
3462 }
3463
3464 nsecs_t currentTime = now();
3465
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003466 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003467 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003469 if (cancelationEvents.empty()) {
3470 return;
3471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003473 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3474 "with reality: %s, mode=%d.",
3475 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3476 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003478
3479 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003480 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003481 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3482 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003483 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003484 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003485 target.globalScaleFactor = windowInfo->globalScaleFactor;
3486 }
3487 target.inputChannel = connection->inputChannel;
3488 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3489
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003490 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003491 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003492 switch (cancelationEventEntry->type) {
3493 case EventEntry::Type::KEY: {
3494 logOutboundKeyDetails("cancel - ",
3495 static_cast<const KeyEntry&>(*cancelationEventEntry));
3496 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003498 case EventEntry::Type::MOTION: {
3499 logOutboundMotionDetails("cancel - ",
3500 static_cast<const MotionEntry&>(*cancelationEventEntry));
3501 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003503 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003504 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3505 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003506 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003507 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003508 break;
3509 }
3510 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003511 case EventEntry::Type::DEVICE_RESET:
3512 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003513 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003514 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003515 break;
3516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
3518
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003519 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3520 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003522
3523 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524}
3525
Svet Ganov5d3bc372020-01-26 23:11:07 -08003526void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3527 const sp<Connection>& connection) {
3528 if (connection->status == Connection::STATUS_BROKEN) {
3529 return;
3530 }
3531
3532 nsecs_t currentTime = now();
3533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003534 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003535 connection->inputState.synthesizePointerDownEvents(currentTime);
3536
3537 if (downEvents.empty()) {
3538 return;
3539 }
3540
3541#if DEBUG_OUTBOUND_EVENT_DETAILS
3542 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3543 connection->getInputChannelName().c_str(), downEvents.size());
3544#endif
3545
3546 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003547 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003548 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3549 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003550 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003551 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003552 target.globalScaleFactor = windowInfo->globalScaleFactor;
3553 }
3554 target.inputChannel = connection->inputChannel;
3555 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3556
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003557 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003558 switch (downEventEntry->type) {
3559 case EventEntry::Type::MOTION: {
3560 logOutboundMotionDetails("down - ",
3561 static_cast<const MotionEntry&>(*downEventEntry));
3562 break;
3563 }
3564
3565 case EventEntry::Type::KEY:
3566 case EventEntry::Type::FOCUS:
3567 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003568 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003569 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003570 case EventEntry::Type::SENSOR:
3571 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003572 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003573 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003574 break;
3575 }
3576 }
3577
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003578 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3579 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003580 }
3581
3582 startDispatchCycleLocked(currentTime, connection);
3583}
3584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003585std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3586 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 ALOG_ASSERT(pointerIds.value != 0);
3588
3589 uint32_t splitPointerIndexMap[MAX_POINTERS];
3590 PointerProperties splitPointerProperties[MAX_POINTERS];
3591 PointerCoords splitPointerCoords[MAX_POINTERS];
3592
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003593 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 uint32_t splitPointerCount = 0;
3595
3596 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003597 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003599 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 uint32_t pointerId = uint32_t(pointerProperties.id);
3601 if (pointerIds.hasBit(pointerId)) {
3602 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3603 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3604 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003605 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 splitPointerCount += 1;
3607 }
3608 }
3609
3610 if (splitPointerCount != pointerIds.count()) {
3611 // This is bad. We are missing some of the pointers that we expected to deliver.
3612 // Most likely this indicates that we received an ACTION_MOVE events that has
3613 // different pointer ids than we expected based on the previous ACTION_DOWN
3614 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3615 // in this way.
3616 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003617 "we expected there to be %d pointers. This probably means we received "
3618 "a broken sequence of pointer ids from the input device.",
3619 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003620 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 }
3622
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003623 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003625 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3626 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3628 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003629 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 uint32_t pointerId = uint32_t(pointerProperties.id);
3631 if (pointerIds.hasBit(pointerId)) {
3632 if (pointerIds.count() == 1) {
3633 // The first/last pointer went down/up.
3634 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003635 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003636 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3637 ? AMOTION_EVENT_ACTION_CANCEL
3638 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 } else {
3640 // A secondary pointer went down/up.
3641 uint32_t splitPointerIndex = 0;
3642 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3643 splitPointerIndex += 1;
3644 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003645 action = maskedAction |
3646 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 }
3648 } else {
3649 // An unrelated pointer changed.
3650 action = AMOTION_EVENT_ACTION_MOVE;
3651 }
3652 }
3653
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003654 int32_t newId = mIdGenerator.nextId();
3655 if (ATRACE_ENABLED()) {
3656 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3657 ") to MotionEvent(id=0x%" PRIx32 ").",
3658 originalMotionEntry.id, newId);
3659 ATRACE_NAME(message.c_str());
3660 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003661 std::unique_ptr<MotionEntry> splitMotionEntry =
3662 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3663 originalMotionEntry.deviceId, originalMotionEntry.source,
3664 originalMotionEntry.displayId,
3665 originalMotionEntry.policyFlags, action,
3666 originalMotionEntry.actionButton,
3667 originalMotionEntry.flags, originalMotionEntry.metaState,
3668 originalMotionEntry.buttonState,
3669 originalMotionEntry.classification,
3670 originalMotionEntry.edgeFlags,
3671 originalMotionEntry.xPrecision,
3672 originalMotionEntry.yPrecision,
3673 originalMotionEntry.xCursorPosition,
3674 originalMotionEntry.yCursorPosition,
3675 originalMotionEntry.downTime, splitPointerCount,
3676 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003678 if (originalMotionEntry.injectionState) {
3679 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 splitMotionEntry->injectionState->refCount += 1;
3681 }
3682
3683 return splitMotionEntry;
3684}
3685
3686void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3687#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003688 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689#endif
3690
3691 bool needWake;
3692 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003693 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003695 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3696 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3697 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 } // release lock
3699
3700 if (needWake) {
3701 mLooper->wake();
3702 }
3703}
3704
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003705/**
3706 * If one of the meta shortcuts is detected, process them here:
3707 * Meta + Backspace -> generate BACK
3708 * Meta + Enter -> generate HOME
3709 * This will potentially overwrite keyCode and metaState.
3710 */
3711void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003712 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003713 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3714 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3715 if (keyCode == AKEYCODE_DEL) {
3716 newKeyCode = AKEYCODE_BACK;
3717 } else if (keyCode == AKEYCODE_ENTER) {
3718 newKeyCode = AKEYCODE_HOME;
3719 }
3720 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003721 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003722 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003723 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003724 keyCode = newKeyCode;
3725 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3726 }
3727 } else if (action == AKEY_EVENT_ACTION_UP) {
3728 // In order to maintain a consistent stream of up and down events, check to see if the key
3729 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3730 // even if the modifier was released between the down and the up events.
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 auto replacementIt = mReplacedKeys.find(replacement);
3734 if (replacementIt != mReplacedKeys.end()) {
3735 keyCode = replacementIt->second;
3736 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003737 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3738 }
3739 }
3740}
3741
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3743#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003744 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3745 "policyFlags=0x%x, action=0x%x, "
3746 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3747 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3748 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3749 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750#endif
3751 if (!validateKeyEvent(args->action)) {
3752 return;
3753 }
3754
3755 uint32_t policyFlags = args->policyFlags;
3756 int32_t flags = args->flags;
3757 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003758 // InputDispatcher tracks and generates key repeats on behalf of
3759 // whatever notifies it, so repeatCount should always be set to 0
3760 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3762 policyFlags |= POLICY_FLAG_VIRTUAL;
3763 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 if (policyFlags & POLICY_FLAG_FUNCTION) {
3766 metaState |= AMETA_FUNCTION_ON;
3767 }
3768
3769 policyFlags |= POLICY_FLAG_TRUSTED;
3770
Michael Wright78f24442014-08-06 15:55:28 -07003771 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003772 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003773
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003775 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003776 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3777 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778
Michael Wright2b3c3302018-03-02 17:19:13 +00003779 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003781 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3782 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 bool needWake;
3787 { // acquire lock
3788 mLock.lock();
3789
3790 if (shouldSendKeyToInputFilterLocked(args)) {
3791 mLock.unlock();
3792
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003793 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3795 return; // event was consumed by the filter
3796 }
3797
3798 mLock.lock();
3799 }
3800
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003801 std::unique_ptr<KeyEntry> newEntry =
3802 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3803 args->displayId, policyFlags, args->action, flags,
3804 keyCode, args->scanCode, metaState, repeatCount,
3805 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003807 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 mLock.unlock();
3809 } // release lock
3810
3811 if (needWake) {
3812 mLooper->wake();
3813 }
3814}
3815
3816bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3817 return mInputFilterEnabled;
3818}
3819
3820void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3821#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003822 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3823 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003824 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3825 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003826 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003827 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3828 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3829 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3830 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 for (uint32_t i = 0; i < args->pointerCount; i++) {
3832 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003833 "x=%f, y=%f, pressure=%f, size=%f, "
3834 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3835 "orientation=%f",
3836 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3837 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3838 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3839 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3840 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3841 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3842 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3843 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3844 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3845 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 }
3847#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3849 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 return;
3851 }
3852
3853 uint32_t policyFlags = args->policyFlags;
3854 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003855
3856 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003857 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003858 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3859 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003860 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862
3863 bool needWake;
3864 { // acquire lock
3865 mLock.lock();
3866
3867 if (shouldSendMotionToInputFilterLocked(args)) {
3868 mLock.unlock();
3869
3870 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003871 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003872 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3873 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003874 args->metaState, args->buttonState, args->classification, transform,
3875 args->xPrecision, args->yPrecision, args->xCursorPosition,
chaviw3277faf2021-05-19 16:45:23 -05003876 args->yCursorPosition, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
3877 args->downTime, args->eventTime, args->pointerCount,
3878 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879
3880 policyFlags |= POLICY_FLAG_FILTERED;
3881 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3882 return; // event was consumed by the filter
3883 }
3884
3885 mLock.lock();
3886 }
3887
3888 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003889 std::unique_ptr<MotionEntry> newEntry =
3890 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3891 args->source, args->displayId, policyFlags,
3892 args->action, args->actionButton, args->flags,
3893 args->metaState, args->buttonState,
3894 args->classification, args->edgeFlags,
3895 args->xPrecision, args->yPrecision,
3896 args->xCursorPosition, args->yCursorPosition,
3897 args->downTime, args->pointerCount,
3898 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003900 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 mLock.unlock();
3902 } // release lock
3903
3904 if (needWake) {
3905 mLooper->wake();
3906 }
3907}
3908
Chris Yef59a2f42020-10-16 12:55:26 -07003909void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3910#if DEBUG_INBOUND_EVENT_DETAILS
3911 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3912 " sensorType=%s",
3913 args->id, args->eventTime, args->deviceId, args->source,
3914 NamedEnum::string(args->sensorType).c_str());
3915#endif
3916
3917 bool needWake;
3918 { // acquire lock
3919 mLock.lock();
3920
3921 // Just enqueue a new sensor event.
3922 std::unique_ptr<SensorEntry> newEntry =
3923 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3924 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3925 args->sensorType, args->accuracy,
3926 args->accuracyChanged, args->values);
3927
3928 needWake = enqueueInboundEventLocked(std::move(newEntry));
3929 mLock.unlock();
3930 } // release lock
3931
3932 if (needWake) {
3933 mLooper->wake();
3934 }
3935}
3936
Chris Yefb552902021-02-03 17:18:37 -08003937void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3938#if DEBUG_INBOUND_EVENT_DETAILS
3939 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3940 args->deviceId, args->isOn);
3941#endif
3942 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3943}
3944
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003946 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947}
3948
3949void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3950#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003951 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003952 "switchMask=0x%08x",
3953 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954#endif
3955
3956 uint32_t policyFlags = args->policyFlags;
3957 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959}
3960
3961void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3962#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003963 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3964 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965#endif
3966
3967 bool needWake;
3968 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003969 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003971 std::unique_ptr<DeviceResetEntry> newEntry =
3972 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3973 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 } // release lock
3975
3976 if (needWake) {
3977 mLooper->wake();
3978 }
3979}
3980
Prabir Pradhan7e186182020-11-10 13:56:45 -08003981void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3982#if DEBUG_INBOUND_EVENT_DETAILS
3983 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3984 args->enabled ? "true" : "false");
3985#endif
3986
Prabir Pradhan99987712020-11-10 18:43:05 -08003987 bool needWake;
3988 { // acquire lock
3989 std::scoped_lock _l(mLock);
3990 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3991 args->enabled);
3992 needWake = enqueueInboundEventLocked(std::move(entry));
3993 } // release lock
3994
3995 if (needWake) {
3996 mLooper->wake();
3997 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003998}
3999
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004000InputEventInjectionResult InputDispatcher::injectInputEvent(
4001 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4002 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003#if DEBUG_INBOUND_EVENT_DETAILS
4004 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004005 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4006 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004008 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009
4010 policyFlags |= POLICY_FLAG_INJECTED;
4011 if (hasInjectionPermission(injectorPid, injectorUid)) {
4012 policyFlags |= POLICY_FLAG_TRUSTED;
4013 }
4014
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004015 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004016 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4017 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4018 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4019 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4020 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004021 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004022 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004023 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004024 }
4025
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004026 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004028 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004029 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4030 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004031 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004032 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004035 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004036 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4037 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4038 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004039 int32_t keyCode = incomingKey.getKeyCode();
4040 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004041 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004042 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004043 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004044 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004045 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4046 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4047 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4050 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004051 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052
4053 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4054 android::base::Timer t;
4055 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4056 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4057 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4058 std::to_string(t.duration().count()).c_str());
4059 }
4060 }
4061
4062 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004063 std::unique_ptr<KeyEntry> injectedEntry =
4064 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004065 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004066 incomingKey.getDisplayId(), policyFlags, action,
4067 flags, keyCode, incomingKey.getScanCode(), metaState,
4068 incomingKey.getRepeatCount(),
4069 incomingKey.getDownTime());
4070 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 }
4073
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004075 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4076 int32_t action = motionEvent.getAction();
4077 size_t pointerCount = motionEvent.getPointerCount();
4078 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4079 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004080 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004081 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004082 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004083 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004084 }
4085
4086 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004087 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004088 android::base::Timer t;
4089 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4090 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4091 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4092 std::to_string(t.duration().count()).c_str());
4093 }
4094 }
4095
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004096 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4097 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4098 }
4099
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004100 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004101 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4102 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004103 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004104 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4105 resolvedDeviceId, motionEvent.getSource(),
4106 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004107 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004108 motionEvent.getButtonState(),
4109 motionEvent.getClassification(),
4110 motionEvent.getEdgeFlags(),
4111 motionEvent.getXPrecision(),
4112 motionEvent.getYPrecision(),
4113 motionEvent.getRawXCursorPosition(),
4114 motionEvent.getRawYCursorPosition(),
4115 motionEvent.getDownTime(), uint32_t(pointerCount),
4116 pointerProperties, samplePointerCoords,
4117 motionEvent.getXOffset(),
4118 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004119 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004120 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004121 sampleEventTimes += 1;
4122 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004123 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004124 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4125 resolvedDeviceId, motionEvent.getSource(),
4126 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004127 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004128 motionEvent.getMetaState(),
4129 motionEvent.getButtonState(),
4130 motionEvent.getClassification(),
4131 motionEvent.getEdgeFlags(),
4132 motionEvent.getXPrecision(),
4133 motionEvent.getYPrecision(),
4134 motionEvent.getRawXCursorPosition(),
4135 motionEvent.getRawYCursorPosition(),
4136 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004137 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004138 samplePointerCoords, motionEvent.getXOffset(),
4139 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004140 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 }
4142 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004146 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004147 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 }
4149
4150 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004151 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 injectionState->injectionIsAsync = true;
4153 }
4154
4155 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004156 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157
4158 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004159 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004160 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004161 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 }
4163
4164 mLock.unlock();
4165
4166 if (needWake) {
4167 mLooper->wake();
4168 }
4169
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004170 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004172 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004174 if (syncMode == InputEventInjectionSync::NONE) {
4175 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 } else {
4177 for (;;) {
4178 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 break;
4181 }
4182
4183 nsecs_t remainingTimeout = endTime - now();
4184 if (remainingTimeout <= 0) {
4185#if DEBUG_INJECTION
4186 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004189 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 }
4192
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004193 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
4195
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004196 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4197 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 while (injectionState->pendingForegroundDispatches != 0) {
4199#if DEBUG_INJECTION
4200 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202#endif
4203 nsecs_t remainingTimeout = endTime - now();
4204 if (remainingTimeout <= 0) {
4205#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4207 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004209 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 break;
4211 }
4212
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004213 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 }
4215 }
4216 }
4217
4218 injectionState->release();
4219 } // release lock
4220
4221#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004222 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224#endif
4225
4226 return injectionResult;
4227}
4228
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004229std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004230 std::array<uint8_t, 32> calculatedHmac;
4231 std::unique_ptr<VerifiedInputEvent> result;
4232 switch (event.getType()) {
4233 case AINPUT_EVENT_TYPE_KEY: {
4234 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4235 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4236 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004237 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004238 break;
4239 }
4240 case AINPUT_EVENT_TYPE_MOTION: {
4241 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4242 VerifiedMotionEvent verifiedMotionEvent =
4243 verifiedMotionEventFromMotionEvent(motionEvent);
4244 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004245 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004246 break;
4247 }
4248 default: {
4249 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4250 return nullptr;
4251 }
4252 }
4253 if (calculatedHmac == INVALID_HMAC) {
4254 return nullptr;
4255 }
4256 if (calculatedHmac != event.getHmac()) {
4257 return nullptr;
4258 }
4259 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004260}
4261
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 return injectorUid == 0 ||
4264 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265}
4266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004268 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004269 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 if (injectionState) {
4271#if DEBUG_INJECTION
4272 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 "injectorPid=%d, injectorUid=%d",
4274 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275#endif
4276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004277 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 // Log the outcome since the injector did not wait for the injection result.
4279 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004280 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 ALOGV("Asynchronous input event injection succeeded.");
4282 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004283 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 ALOGW("Asynchronous input event injection failed.");
4285 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004286 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 ALOGW("Asynchronous input event injection permission denied.");
4288 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004289 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290 ALOGW("Asynchronous input event injection timed out.");
4291 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 case InputEventInjectionResult::PENDING:
4293 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4294 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 }
4296 }
4297
4298 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004299 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301}
4302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004303void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4304 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 if (injectionState) {
4306 injectionState->pendingForegroundDispatches += 1;
4307 }
4308}
4309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004310void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4311 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 if (injectionState) {
4313 injectionState->pendingForegroundDispatches -= 1;
4314
4315 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004316 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
4318 }
4319}
4320
chaviw3277faf2021-05-19 16:45:23 -05004321const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004322 int32_t displayId) const {
chaviw3277faf2021-05-19 16:45:23 -05004323 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004324 auto it = mWindowHandlesByDisplay.find(displayId);
4325 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004326}
4327
chaviw3277faf2021-05-19 16:45:23 -05004328sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004329 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004330 if (windowHandleToken == nullptr) {
4331 return nullptr;
4332 }
4333
Arthur Hungb92218b2018-08-14 12:00:21 +08004334 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004335 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4336 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004337 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004338 return windowHandle;
4339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
4341 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004342 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343}
4344
chaviw3277faf2021-05-19 16:45:23 -05004345sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4346 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004347 if (windowHandleToken == nullptr) {
4348 return nullptr;
4349 }
4350
chaviw3277faf2021-05-19 16:45:23 -05004351 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004352 if (windowHandle->getToken() == windowHandleToken) {
4353 return windowHandle;
4354 }
4355 }
4356 return nullptr;
4357}
4358
chaviw3277faf2021-05-19 16:45:23 -05004359sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4360 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004361 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004362 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4363 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004364 if (handle->getId() == windowHandle->getId() &&
4365 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004366 if (windowHandle->getInfo()->displayId != it.first) {
4367 ALOGE("Found window %s in display %" PRId32
4368 ", but it should belong to display %" PRId32,
4369 windowHandle->getName().c_str(), it.first,
4370 windowHandle->getInfo()->displayId);
4371 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004372 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 }
4375 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004376 return nullptr;
4377}
4378
chaviw3277faf2021-05-19 16:45:23 -05004379sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004380 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4381 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382}
4383
chaviw3277faf2021-05-19 16:45:23 -05004384bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004385 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4386 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004387 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004388 if (connection != nullptr && noInputChannel) {
4389 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4390 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4391 return false;
4392 }
4393
4394 if (connection == nullptr) {
4395 if (!noInputChannel) {
4396 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4397 }
4398 return false;
4399 }
4400 if (!connection->responsive) {
4401 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4402 return false;
4403 }
4404 return true;
4405}
4406
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004407std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4408 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004409 auto connectionIt = mConnectionsByToken.find(token);
4410 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004411 return nullptr;
4412 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004413 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004414}
4415
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004416void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw3277faf2021-05-19 16:45:23 -05004417 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4418 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004419 // Remove all handles on a display if there are no windows left.
4420 mWindowHandlesByDisplay.erase(displayId);
4421 return;
4422 }
4423
4424 // Since we compare the pointer of input window handles across window updates, we need
4425 // to make sure the handle object for the same window stays unchanged across updates.
chaviw3277faf2021-05-19 16:45:23 -05004426 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4427 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4428 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004429 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004430 }
4431
chaviw3277faf2021-05-19 16:45:23 -05004432 std::vector<sp<WindowInfoHandle>> newHandles;
4433 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004434 if (!handle->updateInfo()) {
4435 // handle no longer valid
4436 continue;
4437 }
4438
chaviw3277faf2021-05-19 16:45:23 -05004439 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004440 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4441 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4442 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004443 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4444 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4445 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004446 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004447 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004448 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004449 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004450 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004451 }
4452
4453 if (info->displayId != displayId) {
4454 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4455 handle->getName().c_str(), displayId, info->displayId);
4456 continue;
4457 }
4458
Robert Carredd13602020-04-13 17:24:34 -07004459 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4460 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw3277faf2021-05-19 16:45:23 -05004461 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004462 oldHandle->updateFrom(handle);
4463 newHandles.push_back(oldHandle);
4464 } else {
4465 newHandles.push_back(handle);
4466 }
4467 }
4468
4469 // Insert or replace
4470 mWindowHandlesByDisplay[displayId] = newHandles;
4471}
4472
Arthur Hung72d8dc32020-03-28 00:48:39 +00004473void InputDispatcher::setInputWindows(
chaviw3277faf2021-05-19 16:45:23 -05004474 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004475 { // acquire lock
4476 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004477 for (const auto& [displayId, handles] : handlesPerDisplay) {
4478 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004479 }
4480 }
4481 // Wake up poll loop since it may need to make new input dispatching choices.
4482 mLooper->wake();
4483}
4484
Arthur Hungb92218b2018-08-14 12:00:21 +08004485/**
4486 * Called from InputManagerService, update window handle list by displayId that can receive input.
4487 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4488 * If set an empty list, remove all handles from the specific display.
4489 * For focused handle, check if need to change and send a cancel event to previous one.
4490 * For removed handle, check if need to send a cancel event if already in touch.
4491 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004492void InputDispatcher::setInputWindowsLocked(
chaviw3277faf2021-05-19 16:45:23 -05004493 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004494 if (DEBUG_FOCUS) {
4495 std::string windowList;
chaviw3277faf2021-05-19 16:45:23 -05004496 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004497 windowList += iwh->getName() + " ";
4498 }
4499 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004502 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw3277faf2021-05-19 16:45:23 -05004503 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004504 const bool noInputWindow =
chaviw3277faf2021-05-19 16:45:23 -05004505 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004506 if (noInputWindow && window->getToken() != nullptr) {
4507 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4508 window->getName().c_str());
4509 window->releaseChannel();
4510 }
4511 }
4512
Arthur Hung72d8dc32020-03-28 00:48:39 +00004513 // Copy old handles for release if they are no longer present.
chaviw3277faf2021-05-19 16:45:23 -05004514 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004516 // Save the old windows' orientation by ID before it gets updated.
4517 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw3277faf2021-05-19 16:45:23 -05004518 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004519 oldWindowOrientations.emplace(handle->getId(),
4520 handle->getInfo()->transform.getOrientation());
4521 }
4522
chaviw3277faf2021-05-19 16:45:23 -05004523 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004524
chaviw3277faf2021-05-19 16:45:23 -05004525 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004526 if (mLastHoverWindowHandle &&
4527 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4528 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004529 mLastHoverWindowHandle = nullptr;
4530 }
4531
Vishnu Nairc519ff72021-01-21 08:23:08 -08004532 std::optional<FocusResolver::FocusChanges> changes =
4533 mFocusResolver.setInputWindows(displayId, windowHandles);
4534 if (changes) {
4535 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004538 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4539 mTouchStatesByDisplay.find(displayId);
4540 if (stateIt != mTouchStatesByDisplay.end()) {
4541 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004542 for (size_t i = 0; i < state.windows.size();) {
4543 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004544 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004545 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004546 ALOGD("Touched window was removed: %s in display %" PRId32,
4547 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004548 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004549 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004550 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4551 if (touchedInputChannel != nullptr) {
4552 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4553 "touched window was removed");
4554 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004556 state.windows.erase(state.windows.begin() + i);
4557 } else {
4558 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 }
4560 }
arthurhungb89ccb02020-12-30 16:19:01 +08004561
arthurhung6d4bed92021-03-17 11:59:33 +08004562 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004563 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004564 if (mDragState &&
4565 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004566 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004567 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004568 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004569 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004570
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004571 if (isPerWindowInputRotationEnabled()) {
4572 // Determine if the orientation of any of the input windows have changed, and cancel all
4573 // pointer events if necessary.
chaviw3277faf2021-05-19 16:45:23 -05004574 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4575 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004576 if (newWindowHandle != nullptr &&
4577 newWindowHandle->getInfo()->transform.getOrientation() !=
4578 oldWindowOrientations[oldWindowHandle->getId()]) {
4579 std::shared_ptr<InputChannel> inputChannel =
4580 getInputChannelLocked(newWindowHandle->getToken());
4581 if (inputChannel != nullptr) {
4582 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4583 "touched window's orientation changed");
4584 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4585 }
4586 }
4587 }
4588 }
4589
Arthur Hung72d8dc32020-03-28 00:48:39 +00004590 // Release information for windows that are no longer present.
4591 // This ensures that unused input channels are released promptly.
4592 // Otherwise, they might stick around until the window handle is destroyed
4593 // which might not happen until the next GC.
chaviw3277faf2021-05-19 16:45:23 -05004594 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004595 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004596 if (DEBUG_FOCUS) {
4597 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004598 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004599 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004600 // To avoid making too many calls into the compat framework, only
4601 // check for window flags when windows are going away.
4602 // TODO(b/157929241) : delete this. This is only needed temporarily
4603 // in order to gather some data about the flag usage
chaviw3277faf2021-05-19 16:45:23 -05004604 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004605 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4606 oldWindowHandle->getName().c_str());
4607 if (mCompatService != nullptr) {
4608 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4609 oldWindowHandle->getInfo()->ownerUid);
4610 }
4611 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004612 }
chaviw291d88a2019-02-14 10:33:58 -08004613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614}
4615
4616void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004617 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004618 if (DEBUG_FOCUS) {
4619 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4620 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4621 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004622 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004623 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004624 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 } // release lock
4626
4627 // Wake up poll loop since it may need to make new input dispatching choices.
4628 mLooper->wake();
4629}
4630
Vishnu Nair599f1412021-06-21 10:39:58 -07004631void InputDispatcher::setFocusedApplicationLocked(
4632 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4633 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4634 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4635
4636 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4637 return; // This application is already focused. No need to wake up or change anything.
4638 }
4639
4640 // Set the new application handle.
4641 if (inputApplicationHandle != nullptr) {
4642 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4643 } else {
4644 mFocusedApplicationHandlesByDisplay.erase(displayId);
4645 }
4646
4647 // No matter what the old focused application was, stop waiting on it because it is
4648 // no longer focused.
4649 resetNoFocusedWindowTimeoutLocked();
4650}
4651
Tiger Huang721e26f2018-07-24 22:26:19 +08004652/**
4653 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4654 * the display not specified.
4655 *
4656 * We track any unreleased events for each window. If a window loses the ability to receive the
4657 * released event, we will send a cancel event to it. So when the focused display is changed, we
4658 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4659 * display. The display-specified events won't be affected.
4660 */
4661void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004662 if (DEBUG_FOCUS) {
4663 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4664 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004665 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004666 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004667
4668 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004669 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004670 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004671 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004672 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004673 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004674 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004675 CancelationOptions
4676 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4677 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004678 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004679 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4680 }
4681 }
4682 mFocusedDisplayId = displayId;
4683
Chris Ye3c2d6f52020-08-09 10:39:48 -07004684 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004685 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004686 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004687
Vishnu Nairad321cd2020-08-20 16:40:21 -07004688 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004689 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004690 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004691 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004692 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004693 }
4694 }
4695 }
4696
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004697 if (DEBUG_FOCUS) {
4698 logDispatchStateLocked();
4699 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004700 } // release lock
4701
4702 // Wake up poll loop since it may need to make new input dispatching choices.
4703 mLooper->wake();
4704}
4705
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004707 if (DEBUG_FOCUS) {
4708 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710
4711 bool changed;
4712 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004713 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714
4715 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4716 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004717 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 }
4719
4720 if (mDispatchEnabled && !enabled) {
4721 resetAndDropEverythingLocked("dispatcher is being disabled");
4722 }
4723
4724 mDispatchEnabled = enabled;
4725 mDispatchFrozen = frozen;
4726 changed = true;
4727 } else {
4728 changed = false;
4729 }
4730
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004731 if (DEBUG_FOCUS) {
4732 logDispatchStateLocked();
4733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 } // release lock
4735
4736 if (changed) {
4737 // Wake up poll loop since it may need to make new input dispatching choices.
4738 mLooper->wake();
4739 }
4740}
4741
4742void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004743 if (DEBUG_FOCUS) {
4744 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746
4747 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004748 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749
4750 if (mInputFilterEnabled == enabled) {
4751 return;
4752 }
4753
4754 mInputFilterEnabled = enabled;
4755 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4756 } // release lock
4757
4758 // Wake up poll loop since there might be work to do to drop everything.
4759 mLooper->wake();
4760}
4761
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004762void InputDispatcher::setInTouchMode(bool inTouchMode) {
4763 std::scoped_lock lock(mLock);
4764 mInTouchMode = inTouchMode;
4765}
4766
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004767void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4768 if (opacity < 0 || opacity > 1) {
4769 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4770 return;
4771 }
4772
4773 std::scoped_lock lock(mLock);
4774 mMaximumObscuringOpacityForTouch = opacity;
4775}
4776
4777void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4778 std::scoped_lock lock(mLock);
4779 mBlockUntrustedTouchesMode = mode;
4780}
4781
arthurhungb89ccb02020-12-30 16:19:01 +08004782bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4783 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004784 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004785 if (DEBUG_FOCUS) {
4786 ALOGD("Trivial transfer to same window.");
4787 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004788 return true;
4789 }
4790
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004792 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793
chaviw3277faf2021-05-19 16:45:23 -05004794 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4795 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004796 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004797 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 return false;
4799 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004800 if (DEBUG_FOCUS) {
4801 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4802 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004805 if (DEBUG_FOCUS) {
4806 ALOGD("Cannot transfer focus because windows are on different displays.");
4807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 return false;
4809 }
4810
4811 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004812 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4813 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004814 for (size_t i = 0; i < state.windows.size(); i++) {
4815 const TouchedWindow& touchedWindow = state.windows[i];
4816 if (touchedWindow.windowHandle == fromWindowHandle) {
4817 int32_t oldTargetFlags = touchedWindow.targetFlags;
4818 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004820 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 int32_t newTargetFlags = oldTargetFlags &
4823 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4824 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004825 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826
arthurhungb89ccb02020-12-30 16:19:01 +08004827 // Store the dragging window.
4828 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004829 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004830 }
4831
Jeff Brownf086ddb2014-02-11 14:28:48 -08004832 found = true;
4833 goto Found;
4834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 }
4836 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004837 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004839 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004840 if (DEBUG_FOCUS) {
4841 ALOGD("Focus transfer failed because from window did not have focus.");
4842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 return false;
4844 }
4845
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004846 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4847 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004848 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004849 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004850 CancelationOptions
4851 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4852 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004854 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 }
4856
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004857 if (DEBUG_FOCUS) {
4858 logDispatchStateLocked();
4859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 } // release lock
4861
4862 // Wake up poll loop since it may need to make new input dispatching choices.
4863 mLooper->wake();
4864 return true;
4865}
4866
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004867// Binder call
4868bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4869 sp<IBinder> fromToken;
4870 { // acquire lock
4871 std::scoped_lock _l(mLock);
4872
chaviw3277faf2021-05-19 16:45:23 -05004873 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004874 if (toWindowHandle == nullptr) {
4875 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4876 return false;
4877 }
4878
4879 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4880
4881 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4882 if (touchStateIt == mTouchStatesByDisplay.end()) {
4883 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4884 displayId);
4885 return false;
4886 }
4887
4888 TouchState& state = touchStateIt->second;
4889 if (state.windows.size() != 1) {
4890 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4891 state.windows.size());
4892 return false;
4893 }
4894 const TouchedWindow& touchedWindow = state.windows[0];
4895 fromToken = touchedWindow.windowHandle->getToken();
4896 } // release lock
4897
4898 return transferTouchFocus(fromToken, destChannelToken);
4899}
4900
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004902 if (DEBUG_FOCUS) {
4903 ALOGD("Resetting and dropping all events (%s).", reason);
4904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
4906 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4907 synthesizeCancelationEventsForAllConnectionsLocked(options);
4908
4909 resetKeyRepeatLocked();
4910 releasePendingEventLocked();
4911 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004912 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004915 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004917 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918}
4919
4920void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004921 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 dumpDispatchStateLocked(dump);
4923
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004924 std::istringstream stream(dump);
4925 std::string line;
4926
4927 while (std::getline(stream, line, '\n')) {
4928 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
4930}
4931
Prabir Pradhan99987712020-11-10 18:43:05 -08004932std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4933 std::string dump;
4934
4935 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4936 toString(mFocusedWindowRequestedPointerCapture));
4937
4938 std::string windowName = "None";
4939 if (mWindowTokenWithPointerCapture) {
chaviw3277faf2021-05-19 16:45:23 -05004940 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004941 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4942 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4943 : "token has capture without window";
4944 }
4945 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4946
4947 return dump;
4948}
4949
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004950void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004951 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4952 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4953 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004954 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
Tiger Huang721e26f2018-07-24 22:26:19 +08004956 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4957 dump += StringPrintf(INDENT "FocusedApplications:\n");
4958 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4959 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004960 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004961 const std::chrono::duration timeout =
4962 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004963 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004964 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004965 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004968 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004970
Vishnu Nairc519ff72021-01-21 08:23:08 -08004971 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004972 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004974 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004975 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004976 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4977 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004978 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004979 state.displayId, toString(state.down), toString(state.split),
4980 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004981 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004982 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004983 for (size_t i = 0; i < state.windows.size(); i++) {
4984 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004985 dump += StringPrintf(INDENT4
4986 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4987 i, touchedWindow.windowHandle->getName().c_str(),
4988 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004989 }
4990 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004991 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004992 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004993 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004994 dump += INDENT3 "Portal windows:\n";
4995 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05004996 const sp<WindowInfoHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004997 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4998 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004999 }
5000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001 }
5002 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005003 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004 }
5005
arthurhung6d4bed92021-03-17 11:59:33 +08005006 if (mDragState) {
5007 dump += StringPrintf(INDENT "DragState:\n");
5008 mDragState->dump(dump, INDENT2);
5009 }
5010
Arthur Hungb92218b2018-08-14 12:00:21 +08005011 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005012 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05005013 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005014 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005015 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005016 dump += INDENT2 "Windows:\n";
5017 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005018 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5019 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005021 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005022 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005023 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005024 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005025 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005026 "applicationInfo.name=%s, "
5027 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005028 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005029 i, windowInfo->name.c_str(), windowInfo->id,
5030 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005031 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005032 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005033 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005034 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005035 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005036 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005037 windowInfo->frameLeft, windowInfo->frameTop,
5038 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005039 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005040 windowInfo->applicationInfo.name.c_str(),
5041 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005042 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005043 dump += StringPrintf(", inputFeatures=%s",
5044 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005045 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005046 "ms, trustedOverlay=%s, hasToken=%s, "
5047 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005048 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005049 millis(windowInfo->dispatchingTimeout),
5050 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005051 toString(windowInfo->token != nullptr),
5052 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005053 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005054 }
5055 } else {
5056 dump += INDENT2 "Windows: <none>\n";
5057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 }
5059 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005060 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
5062
Michael Wright3dd60e22019-03-27 22:06:44 +00005063 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005064 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005065 const std::vector<Monitor>& monitors = it.second;
5066 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5067 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005068 }
5069 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005070 const std::vector<Monitor>& monitors = it.second;
5071 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5072 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 }
5077
5078 nsecs_t currentTime = now();
5079
5080 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005081 if (!mRecentQueue.empty()) {
5082 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005083 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005084 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005085 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005086 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 }
5088 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005089 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 }
5091
5092 // Dump event currently being dispatched.
5093 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005094 dump += INDENT "PendingEvent:\n";
5095 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005096 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005097 dump += StringPrintf(", age=%" PRId64 "ms\n",
5098 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005100 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101 }
5102
5103 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005104 if (!mInboundQueue.empty()) {
5105 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005106 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005107 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005108 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005109 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
5111 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005112 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 }
5114
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005115 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005116 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005117 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5118 const KeyReplacement& replacement = pair.first;
5119 int32_t newKeyCode = pair.second;
5120 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005121 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005122 }
5123 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005124 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005125 }
5126
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005127 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005128 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005129 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005130 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005132 connection->inputChannel->getFd().get(),
5133 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005134 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005135 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005137 if (!connection->outboundQueue.empty()) {
5138 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5139 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005140 dump += dumpQueue(connection->outboundQueue, currentTime);
5141
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005143 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 }
5145
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005146 if (!connection->waitQueue.empty()) {
5147 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5148 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005149 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005151 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 }
5153 }
5154 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005155 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 }
5157
5158 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005159 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5160 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005162 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 }
5164
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005166 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5167 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5168 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005169 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005170 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171}
5172
Michael Wright3dd60e22019-03-27 22:06:44 +00005173void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5174 const size_t numMonitors = monitors.size();
5175 for (size_t i = 0; i < numMonitors; i++) {
5176 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005177 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005178 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5179 dump += "\n";
5180 }
5181}
5182
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005183class LooperEventCallback : public LooperCallback {
5184public:
5185 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5186 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5187
5188private:
5189 std::function<int(int events)> mCallback;
5190};
5191
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005192Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005193#if DEBUG_CHANNEL_CREATION
5194 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195#endif
5196
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005197 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005198 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005199 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005200
5201 if (result) {
5202 return base::Error(result) << "Failed to open input channel pair with name " << name;
5203 }
5204
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005206 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005207 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005208 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005209 sp<Connection> connection =
5210 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005212 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5213 ALOGE("Created a new connection, but the token %p is already known", token.get());
5214 }
5215 mConnectionsByToken.emplace(token, connection);
5216
5217 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5218 this, std::placeholders::_1, token);
5219
5220 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221 } // release lock
5222
5223 // Wake the looper because some connections have changed.
5224 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005225 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226}
5227
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005228Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5229 bool isGestureMonitor,
5230 const std::string& name,
5231 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005232 std::shared_ptr<InputChannel> serverChannel;
5233 std::unique_ptr<InputChannel> clientChannel;
5234 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5235 if (result) {
5236 return base::Error(result) << "Failed to open input channel pair with name " << name;
5237 }
5238
Michael Wright3dd60e22019-03-27 22:06:44 +00005239 { // acquire lock
5240 std::scoped_lock _l(mLock);
5241
5242 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005243 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5244 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005245 }
5246
Garfield Tan15601662020-09-22 15:32:38 -07005247 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005248 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005249 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005250
5251 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5252 ALOGE("Created a new connection, but the token %p is already known", token.get());
5253 }
5254 mConnectionsByToken.emplace(token, connection);
5255 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5256 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005258 auto& monitorsByDisplay =
5259 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005260 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005261
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005262 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005263 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5264 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005265 }
Garfield Tan15601662020-09-22 15:32:38 -07005266
Michael Wright3dd60e22019-03-27 22:06:44 +00005267 // Wake the looper because some connections have changed.
5268 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005269 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005270}
5271
Garfield Tan15601662020-09-22 15:32:38 -07005272status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005274 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275
Garfield Tan15601662020-09-22 15:32:38 -07005276 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 if (status) {
5278 return status;
5279 }
5280 } // release lock
5281
5282 // Wake the poll loop because removing the connection may have changed the current
5283 // synchronization state.
5284 mLooper->wake();
5285 return OK;
5286}
5287
Garfield Tan15601662020-09-22 15:32:38 -07005288status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5289 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005290 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005291 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005292 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 return BAD_VALUE;
5294 }
5295
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005296 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005297
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005299 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 }
5301
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005302 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303
5304 nsecs_t currentTime = now();
5305 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5306
5307 connection->status = Connection::STATUS_ZOMBIE;
5308 return OK;
5309}
5310
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005311void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5312 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5313 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005314}
5315
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005316void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005317 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005318 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005319 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005320 std::vector<Monitor>& monitors = it->second;
5321 const size_t numMonitors = monitors.size();
5322 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005323 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005324 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5325 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005326 monitors.erase(monitors.begin() + i);
5327 break;
5328 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005329 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005330 if (monitors.empty()) {
5331 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005332 } else {
5333 ++it;
5334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336}
5337
Michael Wright3dd60e22019-03-27 22:06:44 +00005338status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5339 { // acquire lock
5340 std::scoped_lock _l(mLock);
5341 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5342
5343 if (!foundDisplayId) {
5344 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5345 return BAD_VALUE;
5346 }
5347 int32_t displayId = foundDisplayId.value();
5348
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005349 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5350 mTouchStatesByDisplay.find(displayId);
5351 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005352 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5353 return BAD_VALUE;
5354 }
5355
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005356 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005357 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005358 std::optional<int32_t> foundDeviceId;
5359 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005360 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005361 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005362 foundDeviceId = state.deviceId;
5363 }
5364 }
5365 if (!foundDeviceId || !state.down) {
5366 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005367 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005368 return BAD_VALUE;
5369 }
5370 int32_t deviceId = foundDeviceId.value();
5371
5372 // Send cancel events to all the input channels we're stealing from.
5373 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005374 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005375 options.deviceId = deviceId;
5376 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005377 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005378 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005379 std::shared_ptr<InputChannel> channel =
5380 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005381 if (channel != nullptr) {
5382 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005383 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005384 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005386 canceledWindows += "]";
5387 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5388 canceledWindows.c_str());
5389
Michael Wright3dd60e22019-03-27 22:06:44 +00005390 // Then clear the current touch state so we stop dispatching to them as well.
5391 state.filterNonMonitors();
5392 }
5393 return OK;
5394}
5395
Prabir Pradhan99987712020-11-10 18:43:05 -08005396void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5397 { // acquire lock
5398 std::scoped_lock _l(mLock);
5399 if (DEBUG_FOCUS) {
chaviw3277faf2021-05-19 16:45:23 -05005400 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005401 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5402 windowHandle != nullptr ? windowHandle->getName().c_str()
5403 : "token without window");
5404 }
5405
Vishnu Nairc519ff72021-01-21 08:23:08 -08005406 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005407 if (focusedToken != windowToken) {
5408 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5409 enabled ? "enable" : "disable");
5410 return;
5411 }
5412
5413 if (enabled == mFocusedWindowRequestedPointerCapture) {
5414 ALOGW("Ignoring request to %s Pointer Capture: "
5415 "window has %s requested pointer capture.",
5416 enabled ? "enable" : "disable", enabled ? "already" : "not");
5417 return;
5418 }
5419
5420 mFocusedWindowRequestedPointerCapture = enabled;
5421 setPointerCaptureLocked(enabled);
5422 } // release lock
5423
5424 // Wake the thread to process command entries.
5425 mLooper->wake();
5426}
5427
Michael Wright3dd60e22019-03-27 22:06:44 +00005428std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5429 const sp<IBinder>& token) {
5430 for (const auto& it : mGestureMonitorsByDisplay) {
5431 const std::vector<Monitor>& monitors = it.second;
5432 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005433 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005434 return it.first;
5435 }
5436 }
5437 }
5438 return std::nullopt;
5439}
5440
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005441std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5442 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5443 if (gesturePid.has_value()) {
5444 return gesturePid;
5445 }
5446 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5447}
5448
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005449sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005450 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005451 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005452 }
5453
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005454 for (const auto& [token, connection] : mConnectionsByToken) {
5455 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005456 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457 }
5458 }
Robert Carr4e670e52018-08-15 13:26:12 -07005459
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005460 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461}
5462
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005463std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5464 sp<Connection> connection = getConnectionLocked(connectionToken);
5465 if (connection == nullptr) {
5466 return "<nullptr>";
5467 }
5468 return connection->getInputChannelName();
5469}
5470
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005471void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005472 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005473 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005474}
5475
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005476void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5477 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005478 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005479 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5480 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 commandEntry->connection = connection;
5482 commandEntry->eventTime = currentTime;
5483 commandEntry->seq = seq;
5484 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005485 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005486 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487}
5488
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005489void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5490 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005492 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005494 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5495 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005497 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498}
5499
Vishnu Nairad321cd2020-08-20 16:40:21 -07005500void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5501 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005502 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5503 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005504 commandEntry->oldToken = oldToken;
5505 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005506 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005507}
5508
arthurhungf452d0b2021-01-06 00:19:52 +08005509void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5510 std::unique_ptr<CommandEntry> commandEntry =
5511 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5512 commandEntry->newToken = token;
5513 commandEntry->x = x;
5514 commandEntry->y = y;
5515 postCommandLocked(std::move(commandEntry));
5516}
5517
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005518void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5519 if (connection == nullptr) {
5520 LOG_ALWAYS_FATAL("Caller must check for nullness");
5521 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005522 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5523 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005524 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005525 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005526 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005527 return;
5528 }
5529 /**
5530 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5531 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5532 * has changed. This could cause newer entries to time out before the already dispatched
5533 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5534 * processes the events linearly. So providing information about the oldest entry seems to be
5535 * most useful.
5536 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005537 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005538 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5539 std::string reason =
5540 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005541 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005542 ns2ms(currentWait),
5543 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005544 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005545 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005546
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005547 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5548
5549 // Stop waking up for events on this connection, it is already unresponsive
5550 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005551}
5552
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005553void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5554 std::string reason =
5555 StringPrintf("%s does not have a focused window", application->getName().c_str());
5556 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005557
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005558 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5559 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5560 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005561 postCommandLocked(std::move(commandEntry));
5562}
5563
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005564void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5565 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5566 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5567 commandEntry->obscuringPackage = obscuringPackage;
5568 postCommandLocked(std::move(commandEntry));
5569}
5570
chaviw3277faf2021-05-19 16:45:23 -05005571void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005572 const std::string& reason) {
5573 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5574 updateLastAnrStateLocked(windowLabel, reason);
5575}
5576
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005577void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5578 const std::string& reason) {
5579 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005580 updateLastAnrStateLocked(windowLabel, reason);
5581}
5582
5583void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5584 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005586 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 struct tm tm;
5588 localtime_r(&t, &tm);
5589 char timestr[64];
5590 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005591 mLastAnrState.clear();
5592 mLastAnrState += INDENT "ANR:\n";
5593 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005594 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5595 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005596 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597}
5598
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005599void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 mLock.unlock();
5601
5602 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5603
5604 mLock.lock();
5605}
5606
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005607void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608 sp<Connection> connection = commandEntry->connection;
5609
5610 if (connection->status != Connection::STATUS_ZOMBIE) {
5611 mLock.unlock();
5612
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005613 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614
5615 mLock.lock();
5616 }
5617}
5618
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005619void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005620 sp<IBinder> oldToken = commandEntry->oldToken;
5621 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005622 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005623 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005624 mLock.lock();
5625}
5626
arthurhungf452d0b2021-01-06 00:19:52 +08005627void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5628 sp<IBinder> newToken = commandEntry->newToken;
5629 mLock.unlock();
5630 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5631 mLock.lock();
5632}
5633
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005634void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005636
5637 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5638
5639 mLock.lock();
5640}
5641
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005642void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005643 mLock.unlock();
5644
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005645 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646
5647 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005648}
5649
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005650void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005651 mLock.unlock();
5652
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005653 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5654
5655 mLock.lock();
5656}
5657
5658void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5659 mLock.unlock();
5660
5661 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5662
5663 mLock.lock();
5664}
5665
5666void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5667 mLock.unlock();
5668
5669 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005670
5671 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005672}
5673
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005674void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5675 mLock.unlock();
5676
5677 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5678
5679 mLock.lock();
5680}
5681
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5683 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005684 KeyEntry& entry = *(commandEntry->keyEntry);
5685 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686
5687 mLock.unlock();
5688
Michael Wright2b3c3302018-03-02 17:19:13 +00005689 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005690 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005691 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005692 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5693 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005694 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696
5697 mLock.lock();
5698
5699 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005700 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005702 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005704 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5705 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707}
5708
chaviwfd6d3512019-03-25 13:23:49 -07005709void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5710 mLock.unlock();
5711 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5712 mLock.lock();
5713}
5714
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005715/**
5716 * Connection is responsive if it has no events in the waitQueue that are older than the
5717 * current time.
5718 */
5719static bool isConnectionResponsive(const Connection& connection) {
5720 const nsecs_t currentTime = now();
5721 for (const DispatchEntry* entry : connection.waitQueue) {
5722 if (entry->timeoutTime < currentTime) {
5723 return false;
5724 }
5725 }
5726 return true;
5727}
5728
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005729void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005731 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005733 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005734
5735 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005736 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005737 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005738 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005740 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005741 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005742 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005743 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5744 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005745 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005746 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5747 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5748 connection->inputChannel->getConnectionToken(),
5749 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5750 finishTime);
5751 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005752
5753 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005754 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005755 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005756 restartEvent =
5757 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005758 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005759 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005760 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5761 handled);
5762 } else {
5763 restartEvent = false;
5764 }
5765
5766 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005767 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005768 // contents of the wait queue to have been drained, so we need to double-check
5769 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005770 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5771 if (dispatchEntryIt != connection->waitQueue.end()) {
5772 dispatchEntry = *dispatchEntryIt;
5773 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005774 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5775 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005776 if (!connection->responsive) {
5777 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005778 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005779 // The connection was unresponsive, and now it's responsive.
5780 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005781 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005782 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005783 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005784 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005785 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005786 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005787 } else {
5788 releaseDispatchEntry(dispatchEntry);
5789 }
5790 }
5791
5792 // Start the next dispatch cycle for this connection.
5793 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794}
5795
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005796void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5797 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5798 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5799 monitorUnresponsiveCommand->pid = pid;
5800 monitorUnresponsiveCommand->reason = std::move(reason);
5801 postCommandLocked(std::move(monitorUnresponsiveCommand));
5802}
5803
5804void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5805 std::string reason) {
5806 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5807 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5808 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5809 windowUnresponsiveCommand->reason = std::move(reason);
5810 postCommandLocked(std::move(windowUnresponsiveCommand));
5811}
5812
5813void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5814 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5815 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5816 monitorResponsiveCommand->pid = pid;
5817 postCommandLocked(std::move(monitorResponsiveCommand));
5818}
5819
5820void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5821 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5822 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5823 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5824 postCommandLocked(std::move(windowResponsiveCommand));
5825}
5826
5827/**
5828 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5829 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5830 * command entry to the command queue.
5831 */
5832void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5833 std::string reason) {
5834 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5835 if (connection.monitor) {
5836 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5837 reason.c_str());
5838 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5839 if (!pid.has_value()) {
5840 ALOGE("Could not find unresponsive monitor for connection %s",
5841 connection.inputChannel->getName().c_str());
5842 return;
5843 }
5844 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5845 return;
5846 }
5847 // If not a monitor, must be a window
5848 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5849 reason.c_str());
5850 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5851}
5852
5853/**
5854 * Tell the policy that a connection has become responsive so that it can stop ANR.
5855 */
5856void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5857 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5858 if (connection.monitor) {
5859 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5860 if (!pid.has_value()) {
5861 ALOGE("Could not find responsive monitor for connection %s",
5862 connection.inputChannel->getName().c_str());
5863 return;
5864 }
5865 sendMonitorResponsiveCommandLocked(pid.value());
5866 return;
5867 }
5868 // If not a monitor, must be a window
5869 sendWindowResponsiveCommandLocked(connectionToken);
5870}
5871
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005873 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005874 KeyEntry& keyEntry, bool handled) {
5875 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005876 if (!handled) {
5877 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005878 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005879 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880 return false;
5881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005883 // Get the fallback key state.
5884 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005885 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005886 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005887 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005888 connection->inputState.removeFallbackKey(originalKeyCode);
5889 }
5890
5891 if (handled || !dispatchEntry->hasForegroundTarget()) {
5892 // If the application handles the original key for which we previously
5893 // generated a fallback or if the window is not a foreground window,
5894 // then cancel the associated fallback key, if any.
5895 if (fallbackKeyCode != -1) {
5896 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005898 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005899 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005900 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005902 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005903 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904
5905 mLock.unlock();
5906
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005907 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005908 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909
5910 mLock.lock();
5911
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912 // Cancel the fallback key.
5913 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005915 "application handled the original non-fallback key "
5916 "or is no longer a foreground target, "
5917 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 options.keyCode = fallbackKeyCode;
5919 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005921 connection->inputState.removeFallbackKey(originalKeyCode);
5922 }
5923 } else {
5924 // If the application did not handle a non-fallback key, first check
5925 // that we are in a good state to perform unhandled key event processing
5926 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005927 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005928 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005930 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005931 "since this is not an initial down. "
5932 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005933 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005935 return false;
5936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005938 // Dispatch the unhandled key to the policy.
5939#if DEBUG_OUTBOUND_EVENT_DETAILS
5940 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005941 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005942 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005943#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005944 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005945
5946 mLock.unlock();
5947
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005948 bool fallback =
5949 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005950 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005951
5952 mLock.lock();
5953
5954 if (connection->status != Connection::STATUS_NORMAL) {
5955 connection->inputState.removeFallbackKey(originalKeyCode);
5956 return false;
5957 }
5958
5959 // Latch the fallback keycode for this key on an initial down.
5960 // The fallback keycode cannot change at any other point in the lifecycle.
5961 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005963 fallbackKeyCode = event.getKeyCode();
5964 } else {
5965 fallbackKeyCode = AKEYCODE_UNKNOWN;
5966 }
5967 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5968 }
5969
5970 ALOG_ASSERT(fallbackKeyCode != -1);
5971
5972 // Cancel the fallback key if the policy decides not to send it anymore.
5973 // We will continue to dispatch the key to the policy but we will no
5974 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005975 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5976 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005977#if DEBUG_OUTBOUND_EVENT_DETAILS
5978 if (fallback) {
5979 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005980 "as a fallback for %d, but on the DOWN it had requested "
5981 "to send %d instead. Fallback canceled.",
5982 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005983 } else {
5984 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005985 "but on the DOWN it had requested to send %d. "
5986 "Fallback canceled.",
5987 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988 }
5989#endif
5990
5991 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5992 "canceling fallback, policy no longer desires it");
5993 options.keyCode = fallbackKeyCode;
5994 synthesizeCancelationEventsForConnectionLocked(connection, options);
5995
5996 fallback = false;
5997 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005998 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005999 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006000 }
6001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002
6003#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006004 {
6005 std::string msg;
6006 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6007 connection->inputState.getFallbackKeys();
6008 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006009 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006011 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006012 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006013 }
6014#endif
6015
6016 if (fallback) {
6017 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006018 keyEntry.eventTime = event.getEventTime();
6019 keyEntry.deviceId = event.getDeviceId();
6020 keyEntry.source = event.getSource();
6021 keyEntry.displayId = event.getDisplayId();
6022 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6023 keyEntry.keyCode = fallbackKeyCode;
6024 keyEntry.scanCode = event.getScanCode();
6025 keyEntry.metaState = event.getMetaState();
6026 keyEntry.repeatCount = event.getRepeatCount();
6027 keyEntry.downTime = event.getDownTime();
6028 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006029
6030#if DEBUG_OUTBOUND_EVENT_DETAILS
6031 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006032 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006033 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006034#endif
6035 return true; // restart the event
6036 } else {
6037#if DEBUG_OUTBOUND_EVENT_DETAILS
6038 ALOGD("Unhandled key event: No fallback key.");
6039#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006040
6041 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006042 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043 }
6044 }
6045 return false;
6046}
6047
6048bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006049 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006050 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 return false;
6052}
6053
6054void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6055 mLock.unlock();
6056
Sean Stoutb4e0a592021-02-23 07:34:53 -08006057 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6058 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059
6060 mLock.lock();
6061}
6062
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063void InputDispatcher::traceInboundQueueLengthLocked() {
6064 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006065 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 }
6067}
6068
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006069void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070 if (ATRACE_ENABLED()) {
6071 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006072 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6073 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074 }
6075}
6076
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006077void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006078 if (ATRACE_ENABLED()) {
6079 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006080 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6081 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082 }
6083}
6084
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006085void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006086 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006088 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 dumpDispatchStateLocked(dump);
6090
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006091 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006092 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006093 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094 }
6095}
6096
6097void InputDispatcher::monitor() {
6098 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006099 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006101 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102}
6103
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006104/**
6105 * Wake up the dispatcher and wait until it processes all events and commands.
6106 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6107 * this method can be safely called from any thread, as long as you've ensured that
6108 * the work you are interested in completing has already been queued.
6109 */
6110bool InputDispatcher::waitForIdle() {
6111 /**
6112 * Timeout should represent the longest possible time that a device might spend processing
6113 * events and commands.
6114 */
6115 constexpr std::chrono::duration TIMEOUT = 100ms;
6116 std::unique_lock lock(mLock);
6117 mLooper->wake();
6118 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6119 return result == std::cv_status::no_timeout;
6120}
6121
Vishnu Naire798b472020-07-23 13:52:21 -07006122/**
6123 * Sets focus to the window identified by the token. This must be called
6124 * after updating any input window handles.
6125 *
6126 * Params:
6127 * request.token - input channel token used to identify the window that should gain focus.
6128 * request.focusedToken - the token that the caller expects currently to be focused. If the
6129 * specified token does not match the currently focused window, this request will be dropped.
6130 * If the specified focused token matches the currently focused window, the call will succeed.
6131 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6132 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6133 * when requesting the focus change. This determines which request gets
6134 * precedence if there is a focus change request from another source such as pointer down.
6135 */
Vishnu Nair958da932020-08-21 17:12:37 -07006136void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6137 { // acquire lock
6138 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006139 std::optional<FocusResolver::FocusChanges> changes =
6140 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6141 if (changes) {
6142 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006143 }
6144 } // release lock
6145 // Wake up poll loop since it may need to make new input dispatching choices.
6146 mLooper->wake();
6147}
6148
Vishnu Nairc519ff72021-01-21 08:23:08 -08006149void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6150 if (changes.oldFocus) {
6151 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006152 if (focusedInputChannel) {
6153 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6154 "focus left window");
6155 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006156 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006157 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006158 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006159 if (changes.newFocus) {
6160 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006161 }
6162
Prabir Pradhan99987712020-11-10 18:43:05 -08006163 // If a window has pointer capture, then it must have focus. We need to ensure that this
6164 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6165 // If the window loses focus before it loses pointer capture, then the window can be in a state
6166 // where it has pointer capture but not focus, violating the contract. Therefore we must
6167 // dispatch the pointer capture event before the focus event. Since focus events are added to
6168 // the front of the queue (above), we add the pointer capture event to the front of the queue
6169 // after the focus events are added. This ensures the pointer capture event ends up at the
6170 // front.
6171 disablePointerCaptureForcedLocked();
6172
Vishnu Nairc519ff72021-01-21 08:23:08 -08006173 if (mFocusedDisplayId == changes.displayId) {
6174 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006175 }
6176}
Vishnu Nair958da932020-08-21 17:12:37 -07006177
Prabir Pradhan99987712020-11-10 18:43:05 -08006178void InputDispatcher::disablePointerCaptureForcedLocked() {
6179 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6180 return;
6181 }
6182
6183 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6184
6185 if (mFocusedWindowRequestedPointerCapture) {
6186 mFocusedWindowRequestedPointerCapture = false;
6187 setPointerCaptureLocked(false);
6188 }
6189
6190 if (!mWindowTokenWithPointerCapture) {
6191 // No need to send capture changes because no window has capture.
6192 return;
6193 }
6194
6195 if (mPendingEvent != nullptr) {
6196 // Move the pending event to the front of the queue. This will give the chance
6197 // for the pending event to be dropped if it is a captured event.
6198 mInboundQueue.push_front(mPendingEvent);
6199 mPendingEvent = nullptr;
6200 }
6201
6202 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6203 false /* hasCapture */);
6204 mInboundQueue.push_front(std::move(entry));
6205}
6206
Prabir Pradhan99987712020-11-10 18:43:05 -08006207void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6208 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6209 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6210 commandEntry->enabled = enabled;
6211 postCommandLocked(std::move(commandEntry));
6212}
6213
6214void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6215 android::inputdispatcher::CommandEntry* commandEntry) {
6216 mLock.unlock();
6217
6218 mPolicy->setPointerCapture(commandEntry->enabled);
6219
6220 mLock.lock();
6221}
6222
Vishnu Nair599f1412021-06-21 10:39:58 -07006223void InputDispatcher::displayRemoved(int32_t displayId) {
6224 { // acquire lock
6225 std::scoped_lock _l(mLock);
6226 // Set an empty list to remove all handles from the specific display.
6227 setInputWindowsLocked(/* window handles */ {}, displayId);
6228 setFocusedApplicationLocked(displayId, nullptr);
6229 // Call focus resolver to clean up stale requests. This must be called after input windows
6230 // have been removed for the removed display.
6231 mFocusResolver.displayRemoved(displayId);
6232 } // release lock
6233
6234 // Wake up poll loop since it may need to make new input dispatching choices.
6235 mLooper->wake();
6236}
6237
Garfield Tane84e6f92019-08-29 17:28:41 -07006238} // namespace android::inputdispatcher