blob: 7e069c80d072c72b4da25bc5f4f03e438f039eb9 [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
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080052#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050053#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070054#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100055#include <binder/IServiceManager.h>
56#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080057#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <input/InputWindow.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;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100085using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080086using android::os::InputEventInjectionResult;
87using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100088using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080089
Garfield Tane84e6f92019-08-29 17:28:41 -070090namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Prabir Pradhan93a0f912021-04-21 13:47:42 -070092// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
93// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
94static bool isPerWindowInputRotationEnabled() {
95 static const bool PER_WINDOW_INPUT_ROTATION =
96 base::GetBoolProperty("persist.debug.per_window_input_rotation", false);
97 return PER_WINDOW_INPUT_ROTATION;
98}
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100// Default input dispatching timeout if there is no focused application or paused window
101// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800102const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
103 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
104 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105
106// Amount of time to allow for all pending events to be processed when an app switch
107// key is on the way. This is used to preempt input dispatch and drop input events
108// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
111// Amount of time to allow for an event to be dispatched (measured since its eventTime)
112// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000113constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// 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 +0000116constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
117
118// Log a warning when an interception call takes longer than this to process.
119constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700121// Additional key latency in case a connection is still processing some motion events.
122// This will help with the case when a user touched a button that opens a new window,
123// and gives us the chance to dispatch the key to this new window.
124constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000127constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
128
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000129// Event log tags. See EventLogTags.logtags for reference
130constexpr int LOGTAG_INPUT_INTERACTION = 62000;
131constexpr int LOGTAG_INPUT_FOCUS = 62001;
132
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133static inline nsecs_t now() {
134 return systemTime(SYSTEM_TIME_MONOTONIC);
135}
136
137static inline const char* toString(bool value) {
138 return value ? "true" : "false";
139}
140
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000141static inline const std::string toString(sp<IBinder> binder) {
142 if (binder == nullptr) {
143 return "<null>";
144 }
145 return StringPrintf("%p", binder.get());
146}
147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
150 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151}
152
153static bool isValidKeyAction(int32_t action) {
154 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AKEY_EVENT_ACTION_DOWN:
156 case AKEY_EVENT_ACTION_UP:
157 return true;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
163static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 ALOGE("Key event has invalid action code 0x%x", action);
166 return false;
167 }
168 return true;
169}
170
Michael Wright7b159c92015-05-14 14:48:03 +0100171static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_DOWN:
174 case AMOTION_EVENT_ACTION_UP:
175 case AMOTION_EVENT_ACTION_CANCEL:
176 case AMOTION_EVENT_ACTION_MOVE:
177 case AMOTION_EVENT_ACTION_OUTSIDE:
178 case AMOTION_EVENT_ACTION_HOVER_ENTER:
179 case AMOTION_EVENT_ACTION_HOVER_MOVE:
180 case AMOTION_EVENT_ACTION_HOVER_EXIT:
181 case AMOTION_EVENT_ACTION_SCROLL:
182 return true;
183 case AMOTION_EVENT_ACTION_POINTER_DOWN:
184 case AMOTION_EVENT_ACTION_POINTER_UP: {
185 int32_t index = getMotionEventActionPointerIndex(action);
186 return index >= 0 && index < pointerCount;
187 }
188 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
189 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
190 return actionButton != 0;
191 default:
192 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 }
194}
195
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500196static int64_t millis(std::chrono::nanoseconds t) {
197 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
198}
199
Michael Wright7b159c92015-05-14 14:48:03 +0100200static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700201 const PointerProperties* pointerProperties) {
202 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 ALOGE("Motion event has invalid action code 0x%x", action);
204 return false;
205 }
206 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000207 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700208 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 return false;
210 }
211 BitSet32 pointerIdBits;
212 for (size_t i = 0; i < pointerCount; i++) {
213 int32_t id = pointerProperties[i].id;
214 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700215 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
216 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 return false;
218 }
219 if (pointerIdBits.hasBit(id)) {
220 ALOGE("Motion event has duplicate pointer id %d", id);
221 return false;
222 }
223 pointerIdBits.markBit(id);
224 }
225 return true;
226}
227
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000230 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
232
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000233 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 bool first = true;
235 Region::const_iterator cur = region.begin();
236 Region::const_iterator const tail = region.end();
237 while (cur != tail) {
238 if (first) {
239 first = false;
240 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800241 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800243 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 cur++;
245 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000246 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247}
248
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500249static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
250 constexpr size_t maxEntries = 50; // max events to print
251 constexpr size_t skipBegin = maxEntries / 2;
252 const size_t skipEnd = queue.size() - maxEntries / 2;
253 // skip from maxEntries / 2 ... size() - maxEntries/2
254 // only print from 0 .. skipBegin and then from skipEnd .. size()
255
256 std::string dump;
257 for (size_t i = 0; i < queue.size(); i++) {
258 const DispatchEntry& entry = *queue[i];
259 if (i >= skipBegin && i < skipEnd) {
260 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
261 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
262 continue;
263 }
264 dump.append(INDENT4);
265 dump += entry.eventEntry->getDescription();
266 dump += StringPrintf(", seq=%" PRIu32
267 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
268 entry.seq, entry.targetFlags, entry.resolvedAction,
269 ns2ms(currentTime - entry.eventEntry->eventTime));
270 if (entry.deliveryTime != 0) {
271 // This entry was delivered, so add information on how long we've been waiting
272 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
273 }
274 dump.append("\n");
275 }
276 return dump;
277}
278
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700279/**
280 * Find the entry in std::unordered_map by key, and return it.
281 * If the entry is not found, return a default constructed entry.
282 *
283 * Useful when the entries are vectors, since an empty vector will be returned
284 * if the entry is not found.
285 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
286 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700287template <typename K, typename V>
288static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700289 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700290 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800291}
292
chaviwaf87b3e2019-10-01 16:59:28 -0700293static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
294 if (first == second) {
295 return true;
296 }
297
298 if (first == nullptr || second == nullptr) {
299 return false;
300 }
301
302 return first->getToken() == second->getToken();
303}
304
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000305static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
306 if (first == nullptr || second == nullptr) {
307 return false;
308 }
309 return first->applicationInfo.token != nullptr &&
310 first->applicationInfo.token == second->applicationInfo.token;
311}
312
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800313static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
314 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
315}
316
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700318 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900320 if (eventEntry->type == EventEntry::Type::MOTION) {
321 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800322 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900323 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800324 // Use identity transform for events that are not pointer events because their axes
325 // values do not represent on-screen coordinates, so they should not have any window
326 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900327 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700328 1.0f /*globalScaleFactor*/,
329 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900330 }
331 }
332
chaviw1ff3d1e2020-07-01 15:53:47 -0700333 if (inputTarget.useDefaultPointerTransform()) {
334 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700335 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700336 inputTarget.globalScaleFactor,
337 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 }
339
340 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
341 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700343 std::vector<PointerCoords> pointerCoords;
344 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 // Use the first pointer information to normalize all other pointers. This could be any pointer
347 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700348 // uses the transform for the normalized pointer.
349 const ui::Transform& firstPointerTransform =
350 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
351 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352
353 // Iterate through all pointers in the event to normalize against the first.
354 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
355 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
356 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358
359 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700360 // First, apply the current pointer's transform to update the coordinates into
361 // window space.
362 pointerCoords[pointerIndex].transform(currTransform);
363 // Next, apply the inverse transform of the normalized coordinates so the
364 // current coordinates are transformed into the normalized coordinate space.
365 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366 }
367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700368 std::unique_ptr<MotionEntry> combinedMotionEntry =
369 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
370 motionEntry.deviceId, motionEntry.source,
371 motionEntry.displayId, motionEntry.policyFlags,
372 motionEntry.action, motionEntry.actionButton,
373 motionEntry.flags, motionEntry.metaState,
374 motionEntry.buttonState, motionEntry.classification,
375 motionEntry.edgeFlags, motionEntry.xPrecision,
376 motionEntry.yPrecision, motionEntry.xCursorPosition,
377 motionEntry.yCursorPosition, motionEntry.downTime,
378 motionEntry.pointerCount, motionEntry.pointerProperties,
379 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 if (motionEntry.injectionState) {
382 combinedMotionEntry->injectionState = motionEntry.injectionState;
383 combinedMotionEntry->injectionState->refCount += 1;
384 }
385
386 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700387 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700388 firstPointerTransform, inputTarget.globalScaleFactor,
389 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 return dispatchEntry;
391}
392
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700393static void addGestureMonitors(const std::vector<Monitor>& monitors,
394 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
395 float yOffset = 0) {
396 if (monitors.empty()) {
397 return;
398 }
399 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
400 for (const Monitor& monitor : monitors) {
401 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
402 }
403}
404
Garfield Tan15601662020-09-22 15:32:38 -0700405static status_t openInputChannelPair(const std::string& name,
406 std::shared_ptr<InputChannel>& serverChannel,
407 std::unique_ptr<InputChannel>& clientChannel) {
408 std::unique_ptr<InputChannel> uniqueServerChannel;
409 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
410
411 serverChannel = std::move(uniqueServerChannel);
412 return result;
413}
414
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500415template <typename T>
416static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
417 if (lhs == nullptr && rhs == nullptr) {
418 return true;
419 }
420 if (lhs == nullptr || rhs == nullptr) {
421 return false;
422 }
423 return *lhs == *rhs;
424}
425
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000426static sp<IPlatformCompatNative> getCompatService() {
427 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
428 if (service == nullptr) {
429 ALOGE("Failed to link to compat service");
430 return nullptr;
431 }
432 return interface_cast<IPlatformCompatNative>(service);
433}
434
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000435static KeyEvent createKeyEvent(const KeyEntry& entry) {
436 KeyEvent event;
437 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
438 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
439 entry.repeatCount, entry.downTime, entry.eventTime);
440 return event;
441}
442
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000443static std::optional<int32_t> findMonitorPidByToken(
444 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
445 const sp<IBinder>& token) {
446 for (const auto& it : monitorsByDisplay) {
447 const std::vector<Monitor>& monitors = it.second;
448 for (const Monitor& monitor : monitors) {
449 if (monitor.inputChannel->getConnectionToken() == token) {
450 return monitor.pid;
451 }
452 }
453 }
454 return std::nullopt;
455}
456
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000457static bool shouldReportMetricsForConnection(const Connection& connection) {
458 // Do not keep track of gesture monitors. They receive every event and would disproportionately
459 // affect the statistics.
460 if (connection.monitor) {
461 return false;
462 }
463 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
464 if (!connection.responsive) {
465 return false;
466 }
467 return true;
468}
469
470static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
471 const Connection& connection) {
472 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
473 const int32_t& inputEventId = eventEntry.id;
474 if (inputEventId != dispatchEntry.resolvedEventId) {
475 // Event was transmuted
476 return false;
477 }
478 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
479 return false;
480 }
481 // Only track latency for events that originated from hardware
482 if (eventEntry.isSynthesized()) {
483 return false;
484 }
485 const EventEntry::Type& inputEventEntryType = eventEntry.type;
486 if (inputEventEntryType == EventEntry::Type::KEY) {
487 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
488 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
489 return false;
490 }
491 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
492 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
493 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
494 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
495 return false;
496 }
497 } else {
498 // Not a key or a motion
499 return false;
500 }
501 if (!shouldReportMetricsForConnection(connection)) {
502 return false;
503 }
504 return true;
505}
506
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507// --- InputDispatcher ---
508
Garfield Tan00f511d2019-06-12 16:55:40 -0700509InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
510 : mPolicy(policy),
511 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700512 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800513 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700514 mAppSwitchSawKeyDown(false),
515 mAppSwitchDueTime(LONG_LONG_MAX),
516 mNextUnblockedEvent(nullptr),
517 mDispatchEnabled(false),
518 mDispatchFrozen(false),
519 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800520 // mInTouchMode will be initialized by the WindowManager to the default device config.
521 // To avoid leaking stack in case that call never comes, and for tests,
522 // initialize it here anyways.
523 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100524 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000525 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800526 mFocusedWindowRequestedPointerCapture(false),
527 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000528 mLatencyAggregator(),
529 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000530 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800532 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
Yi Kong9b14ac62018-07-17 13:48:38 -0700534 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535
536 policy->getDispatcherConfiguration(&mConfig);
537}
538
539InputDispatcher::~InputDispatcher() {
540 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800541 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542
543 resetKeyRepeatLocked();
544 releasePendingEventLocked();
545 drainInboundQueueLocked();
546 }
547
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000548 while (!mConnectionsByToken.empty()) {
549 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700550 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 }
552}
553
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700554status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700555 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700556 return ALREADY_EXISTS;
557 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700558 mThread = std::make_unique<InputThread>(
559 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
560 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700561}
562
563status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700564 if (mThread && mThread->isCallingThread()) {
565 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700566 return INVALID_OPERATION;
567 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700568 mThread.reset();
569 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700570}
571
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572void InputDispatcher::dispatchOnce() {
573 nsecs_t nextWakeupTime = LONG_LONG_MAX;
574 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800575 std::scoped_lock _l(mLock);
576 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
578 // Run a dispatch loop if there are no pending commands.
579 // The dispatch loop might enqueue commands to run afterwards.
580 if (!haveCommandsLocked()) {
581 dispatchOnceInnerLocked(&nextWakeupTime);
582 }
583
584 // Run all pending commands if there are any.
585 // If any commands were run then force the next poll to wake up immediately.
586 if (runCommandsLockedInterruptible()) {
587 nextWakeupTime = LONG_LONG_MIN;
588 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800589
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700590 // If we are still waiting for ack on some events,
591 // we might have to wake up earlier to check if an app is anr'ing.
592 const nsecs_t nextAnrCheck = processAnrsLocked();
593 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
594
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800595 // We are about to enter an infinitely long sleep, because we have no commands or
596 // pending or queued events
597 if (nextWakeupTime == LONG_LONG_MAX) {
598 mDispatcherEnteredIdle.notify_all();
599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 } // release lock
601
602 // Wait for callback or timeout or wake. (make sure we round up, not down)
603 nsecs_t currentTime = now();
604 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
605 mLooper->pollOnce(timeoutMillis);
606}
607
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700608/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500609 * Raise ANR if there is no focused window.
610 * Before the ANR is raised, do a final state check:
611 * 1. The currently focused application must be the same one we are waiting for.
612 * 2. Ensure we still don't have a focused window.
613 */
614void InputDispatcher::processNoFocusedWindowAnrLocked() {
615 // Check if the application that we are waiting for is still focused.
616 std::shared_ptr<InputApplicationHandle> focusedApplication =
617 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
618 if (focusedApplication == nullptr ||
619 focusedApplication->getApplicationToken() !=
620 mAwaitedFocusedApplication->getApplicationToken()) {
621 // Unexpected because we should have reset the ANR timer when focused application changed
622 ALOGE("Waited for a focused window, but focused application has already changed to %s",
623 focusedApplication->getName().c_str());
624 return; // The focused application has changed.
625 }
626
627 const sp<InputWindowHandle>& focusedWindowHandle =
628 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
629 if (focusedWindowHandle != nullptr) {
630 return; // We now have a focused window. No need for ANR.
631 }
632 onAnrLocked(mAwaitedFocusedApplication);
633}
634
635/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700636 * Check if any of the connections' wait queues have events that are too old.
637 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
638 * Return the time at which we should wake up next.
639 */
640nsecs_t InputDispatcher::processAnrsLocked() {
641 const nsecs_t currentTime = now();
642 nsecs_t nextAnrCheck = LONG_LONG_MAX;
643 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
644 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
645 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500646 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700647 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500648 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700649 return LONG_LONG_MIN;
650 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500651 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700652 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
653 }
654 }
655
656 // Check if any connection ANRs are due
657 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
658 if (currentTime < nextAnrCheck) { // most likely scenario
659 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
660 }
661
662 // If we reached here, we have an unresponsive connection.
663 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
664 if (connection == nullptr) {
665 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
666 return nextAnrCheck;
667 }
668 connection->responsive = false;
669 // Stop waking up for this unresponsive connection
670 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000671 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700672 return LONG_LONG_MIN;
673}
674
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500675std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700676 sp<InputWindowHandle> window = getWindowHandleLocked(token);
677 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500678 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700679 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500680 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700681}
682
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
684 nsecs_t currentTime = now();
685
Jeff Browndc5992e2014-04-11 01:27:26 -0700686 // Reset the key repeat timer whenever normal dispatch is suspended while the
687 // device is in a non-interactive state. This is to ensure that we abort a key
688 // repeat if the device is just coming out of sleep.
689 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 resetKeyRepeatLocked();
691 }
692
693 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
694 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100695 if (DEBUG_FOCUS) {
696 ALOGD("Dispatch frozen. Waiting some more.");
697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 return;
699 }
700
701 // Optimize latency of app switches.
702 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
703 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
704 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
705 if (mAppSwitchDueTime < *nextWakeupTime) {
706 *nextWakeupTime = mAppSwitchDueTime;
707 }
708
709 // Ready to start a new event.
710 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700712 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 if (isAppSwitchDue) {
714 // The inbound queue is empty so the app switch key we were waiting
715 // for will never arrive. Stop waiting for it.
716 resetPendingAppSwitchLocked(false);
717 isAppSwitchDue = false;
718 }
719
720 // Synthesize a key repeat if appropriate.
721 if (mKeyRepeatState.lastKeyEntry) {
722 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
723 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
724 } else {
725 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
726 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
727 }
728 }
729 }
730
731 // Nothing to do if there is no pending event.
732 if (!mPendingEvent) {
733 return;
734 }
735 } else {
736 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700737 mPendingEvent = mInboundQueue.front();
738 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 traceInboundQueueLengthLocked();
740 }
741
742 // Poke user activity for this event.
743 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700744 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 }
747
748 // Now we have an event to dispatch.
749 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700750 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700752 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700754 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700756 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 }
758
759 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700760 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 }
762
763 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700764 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700765 const ConfigurationChangedEntry& typedEntry =
766 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700767 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700768 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 break;
770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700773 const DeviceResetEntry& typedEntry =
774 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700776 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100780 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700781 std::shared_ptr<FocusEntry> typedEntry =
782 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100783 dispatchFocusLocked(currentTime, typedEntry);
784 done = true;
785 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
786 break;
787 }
788
Prabir Pradhan99987712020-11-10 18:43:05 -0800789 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
790 const auto typedEntry =
791 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
792 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
793 done = true;
794 break;
795 }
796
arthurhungb89ccb02020-12-30 16:19:01 +0800797 case EventEntry::Type::DRAG: {
798 std::shared_ptr<DragEntry> typedEntry =
799 std::static_pointer_cast<DragEntry>(mPendingEvent);
800 dispatchDragLocked(currentTime, typedEntry);
801 done = true;
802 break;
803 }
804
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700805 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700806 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 resetPendingAppSwitchLocked(true);
810 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 } else if (dropReason == DropReason::NOT_DROPPED) {
812 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 }
814 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700815 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700818 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
819 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700821 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 break;
823 }
824
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700825 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700826 std::shared_ptr<MotionEntry> motionEntry =
827 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700828 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
829 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700831 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700832 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
835 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700836 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700837 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
Chris Yef59a2f42020-10-16 12:55:26 -0700840
841 case EventEntry::Type::SENSOR: {
842 std::shared_ptr<SensorEntry> sensorEntry =
843 std::static_pointer_cast<SensorEntry>(mPendingEvent);
844 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
845 dropReason = DropReason::APP_SWITCH;
846 }
847 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
848 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
849 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
850 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
851 dropReason = DropReason::STALE;
852 }
853 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
854 done = true;
855 break;
856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 }
858
859 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700860 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700861 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
Michael Wright3a981722015-06-10 15:26:13 +0100863 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864
865 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
868}
869
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700870/**
871 * Return true if the events preceding this incoming motion event should be dropped
872 * Return false otherwise (the default behaviour)
873 */
874bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700875 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700876 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877
878 // Optimize case where the current application is unresponsive and the user
879 // decides to touch a window in a different application.
880 // If the application takes too long to catch up then we drop all events preceding
881 // the touch into the other window.
882 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700883 int32_t displayId = motionEntry.displayId;
884 int32_t x = static_cast<int32_t>(
885 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
886 int32_t y = static_cast<int32_t>(
887 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
888 sp<InputWindowHandle> touchedWindowHandle =
889 findTouchedWindowAtLocked(displayId, x, y, nullptr);
890 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891 touchedWindowHandle->getApplicationToken() !=
892 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700893 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700894 ALOGI("Pruning input queue because user touched a different application while waiting "
895 "for %s",
896 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700897 return true;
898 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899
900 // Alternatively, maybe there's a gesture monitor that could handle this event
901 std::vector<TouchedMonitor> gestureMonitors =
902 findTouchedGestureMonitorsLocked(displayId, {});
903 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
904 sp<Connection> connection =
905 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000906 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907 // This monitor could take more input. Drop all events preceding this
908 // event, so that gesture monitor could get a chance to receive the stream
909 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
910 "responsive gesture monitor that may handle the event",
911 mAwaitedFocusedApplication->getName().c_str());
912 return true;
913 }
914 }
915 }
916
917 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
918 // yet been processed by some connections, the dispatcher will wait for these motion
919 // events to be processed before dispatching the key event. This is because these motion events
920 // may cause a new window to be launched, which the user might expect to receive focus.
921 // To prevent waiting forever for such events, just send the key to the currently focused window
922 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
923 ALOGD("Received a new pointer down event, stop waiting for events to process and "
924 "just send the pending key event to the focused window.");
925 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 }
927 return false;
928}
929
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700930bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700931 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700932 mInboundQueue.push_back(std::move(newEntry));
933 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 traceInboundQueueLengthLocked();
935
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700936 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700937 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 // Optimize app switch latency.
939 // If the application takes too long to catch up then we drop all events preceding
940 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700941 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700942 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700943 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700945 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700948 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700950 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 mAppSwitchSawKeyDown = false;
952 needWake = true;
953 }
954 }
955 }
956 break;
957 }
958
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700959 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700960 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
961 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700962 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100966 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700967 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
968 break;
969 }
970 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800971 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700972 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800973 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
974 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700975 // nothing to do
976 break;
977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
979
980 return needWake;
981}
982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700984 // Do not store sensor event in recent queue to avoid flooding the queue.
985 if (entry->type != EventEntry::Type::SENSOR) {
986 mRecentQueue.push_back(entry);
987 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700988 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700989 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
991}
992
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700994 int32_t y, TouchState* touchState,
995 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800996 bool addPortalWindows,
997 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700998 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
999 LOG_ALWAYS_FATAL(
1000 "Must provide a valid touch state if adding portal windows or outside targets");
1001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -07001003 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001004 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001005 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001006 continue;
1007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1009 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001010 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011
1012 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001013 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1014 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1015 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001017 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1019 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001020 if (addPortalWindows) {
1021 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001022 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001023 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001024 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 // Found window.
1028 return windowHandle;
1029 }
1030 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001031
Michael Wright44753b12020-07-08 13:48:11 +01001032 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001033 touchState->addOrUpdateWindow(windowHandle,
1034 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1035 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041}
1042
Garfield Tane84e6f92019-08-29 17:28:41 -07001043std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001044 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001045 std::vector<TouchedMonitor> touchedMonitors;
1046
1047 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1048 addGestureMonitors(monitors, touchedMonitors);
1049 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1050 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1051 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1053 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001054 }
1055 return touchedMonitors;
1056}
1057
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001058void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 const char* reason;
1060 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001061 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001063 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 reason = "inbound event was dropped because the policy consumed it";
1066 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001067 case DropReason::DISABLED:
1068 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 ALOGI("Dropped event because input dispatch is disabled.");
1070 }
1071 reason = "inbound event was dropped because input dispatch is disabled";
1072 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001073 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 ALOGI("Dropped event because of pending overdue app switch.");
1075 reason = "inbound event was dropped because of pending overdue app switch";
1076 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 ALOGI("Dropped event because the current application is not responding and the user "
1079 "has started interacting with a different application.");
1080 reason = "inbound event was dropped because the current application is not responding "
1081 "and the user has started interacting with a different application";
1082 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 ALOGI("Dropped event because it is stale.");
1085 reason = "inbound event was dropped because it is stale";
1086 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001087 case DropReason::NO_POINTER_CAPTURE:
1088 ALOGI("Dropped event because there is no window with Pointer Capture.");
1089 reason = "inbound event was dropped because there is no window with Pointer Capture";
1090 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 case DropReason::NOT_DROPPED: {
1092 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001097 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001098 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1100 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001103 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1105 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1107 synthesizeCancelationEventsForAllConnectionsLocked(options);
1108 } else {
1109 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1110 synthesizeCancelationEventsForAllConnectionsLocked(options);
1111 }
1112 break;
1113 }
Chris Yef59a2f42020-10-16 12:55:26 -07001114 case EventEntry::Type::SENSOR: {
1115 break;
1116 }
arthurhungb89ccb02020-12-30 16:19:01 +08001117 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1118 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001119 break;
1120 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001121 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001122 case EventEntry::Type::CONFIGURATION_CHANGED:
1123 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001124 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001125 break;
1126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128}
1129
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001130static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1132 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133}
1134
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001135bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1136 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1137 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1138 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139}
1140
1141bool InputDispatcher::isAppSwitchPendingLocked() {
1142 return mAppSwitchDueTime != LONG_LONG_MAX;
1143}
1144
1145void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1146 mAppSwitchDueTime = LONG_LONG_MAX;
1147
1148#if DEBUG_APP_SWITCH
1149 if (handled) {
1150 ALOGD("App switch has arrived.");
1151 } else {
1152 ALOGD("App switch was abandoned.");
1153 }
1154#endif
1155}
1156
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001158 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159}
1160
1161bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001162 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 return false;
1164 }
1165
1166 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001167 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001168 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001170 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171
1172 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001173 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 return true;
1175}
1176
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001177void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1178 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179}
1180
1181void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001182 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001183 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001184 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 releaseInboundEventLocked(entry);
1186 }
1187 traceInboundQueueLengthLocked();
1188}
1189
1190void InputDispatcher::releasePendingEventLocked() {
1191 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001193 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195}
1196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001199 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200#if DEBUG_DISPATCH_CYCLE
1201 ALOGD("Injected inbound event was dropped.");
1202#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 }
1205 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001206 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
1208 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209}
1210
1211void InputDispatcher::resetKeyRepeatLocked() {
1212 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001213 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 }
1215}
1216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1218 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
Michael Wright2e732952014-09-24 13:26:59 -07001220 uint32_t policyFlags = entry->policyFlags &
1221 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223 std::shared_ptr<KeyEntry> newEntry =
1224 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1225 entry->source, entry->displayId, policyFlags, entry->action,
1226 entry->flags, entry->keyCode, entry->scanCode,
1227 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001229 newEntry->syntheticRepeat = true;
1230 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001232 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239#endif
1240
1241 // Reset key repeating in case a keyboard device was added or removed or something.
1242 resetKeyRepeatLocked();
1243
1244 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001245 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1246 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001248 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 return true;
1250}
1251
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1253 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1256 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257#endif
1258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 synthesizeCancelationEventsForAllConnectionsLocked(options);
1262 return true;
1263}
1264
Vishnu Nairad321cd2020-08-20 16:40:21 -07001265void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001266 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001267 if (mPendingEvent != nullptr) {
1268 // Move the pending event to the front of the queue. This will give the chance
1269 // for the pending event to get dispatched to the newly focused window
1270 mInboundQueue.push_front(mPendingEvent);
1271 mPendingEvent = nullptr;
1272 }
1273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 std::unique_ptr<FocusEntry> focusEntry =
1275 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1276 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001277
1278 // This event should go to the front of the queue, but behind all other focus events
1279 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001281 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282 [](const std::shared_ptr<EventEntry>& event) {
1283 return event->type == EventEntry::Type::FOCUS;
1284 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001285
1286 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001288}
1289
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001291 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001292 if (channel == nullptr) {
1293 return; // Window has gone away
1294 }
1295 InputTarget target;
1296 target.inputChannel = channel;
1297 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1298 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001299 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1300 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001301 std::string reason = std::string("reason=").append(entry->reason);
1302 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001303 dispatchEventLocked(currentTime, entry, {target});
1304}
1305
Prabir Pradhan99987712020-11-10 18:43:05 -08001306void InputDispatcher::dispatchPointerCaptureChangedLocked(
1307 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1308 DropReason& dropReason) {
1309 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001310 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1311 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1312 }
1313 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001314 // Pointer capture was already forcefully disabled because of focus change.
1315 dropReason = DropReason::NOT_DROPPED;
1316 return;
1317 }
1318
1319 // Set drop reason for early returns
1320 dropReason = DropReason::NO_POINTER_CAPTURE;
1321
1322 sp<IBinder> token;
1323 if (entry->pointerCaptureEnabled) {
1324 // Enable Pointer Capture
1325 if (!mFocusedWindowRequestedPointerCapture) {
1326 // This can happen if a window requests capture and immediately releases capture.
1327 ALOGW("No window requested Pointer Capture.");
1328 return;
1329 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001330 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001331 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1332 mWindowTokenWithPointerCapture = token;
1333 } else {
1334 // Disable Pointer Capture
1335 token = mWindowTokenWithPointerCapture;
1336 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001337 if (mFocusedWindowRequestedPointerCapture) {
1338 mFocusedWindowRequestedPointerCapture = false;
1339 setPointerCaptureLocked(false);
1340 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001341 }
1342
1343 auto channel = getInputChannelLocked(token);
1344 if (channel == nullptr) {
1345 // Window has gone away, clean up Pointer Capture state.
1346 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001347 if (mFocusedWindowRequestedPointerCapture) {
1348 mFocusedWindowRequestedPointerCapture = false;
1349 setPointerCaptureLocked(false);
1350 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001351 return;
1352 }
1353 InputTarget target;
1354 target.inputChannel = channel;
1355 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1356 entry->dispatchInProgress = true;
1357 dispatchEventLocked(currentTime, entry, {target});
1358
1359 dropReason = DropReason::NOT_DROPPED;
1360}
1361
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001362bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001363 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 if (!entry->dispatchInProgress) {
1366 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1367 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1368 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1369 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001370 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 // We have seen two identical key downs in a row which indicates that the device
1372 // driver is automatically generating key repeats itself. We take note of the
1373 // repeat here, but we disable our own next key repeat timer since it is clear that
1374 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001375 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1376 // Make sure we don't get key down from a different device. If a different
1377 // device Id has same key pressed down, the new device Id will replace the
1378 // current one to hold the key repeat with repeat count reset.
1379 // In the future when got a KEY_UP on the device id, drop it and do not
1380 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1382 resetKeyRepeatLocked();
1383 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1384 } else {
1385 // Not a repeat. Save key down state in case we do see a repeat later.
1386 resetKeyRepeatLocked();
1387 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1388 }
1389 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001390 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1391 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001392 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001393#if DEBUG_INBOUND_EVENT_DETAILS
1394 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1395#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001396 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 resetKeyRepeatLocked();
1398 }
1399
1400 if (entry->repeatCount == 1) {
1401 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1402 } else {
1403 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1404 }
1405
1406 entry->dispatchInProgress = true;
1407
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001408 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 }
1410
1411 // Handle case where the policy asked us to try again later last time.
1412 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1413 if (currentTime < entry->interceptKeyWakeupTime) {
1414 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1415 *nextWakeupTime = entry->interceptKeyWakeupTime;
1416 }
1417 return false; // wait until next wakeup
1418 }
1419 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1420 entry->interceptKeyWakeupTime = 0;
1421 }
1422
1423 // Give the policy a chance to intercept the key.
1424 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1425 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001426 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001427 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001428 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001429 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001430 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001432 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 return false; // wait for the command to run
1434 } else {
1435 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1436 }
1437 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001438 if (*dropReason == DropReason::NOT_DROPPED) {
1439 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 }
1441 }
1442
1443 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001444 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001445 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001446 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1447 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001448 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 return true;
1450 }
1451
1452 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001453 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001454 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001455 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001456 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 return false;
1458 }
1459
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001460 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 return true;
1463 }
1464
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001465 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001466 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467
1468 // Dispatch the key.
1469 dispatchEventLocked(currentTime, entry, inputTargets);
1470 return true;
1471}
1472
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001473void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001475 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001476 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1477 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1479 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1480 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481#endif
1482}
1483
Chris Yef59a2f42020-10-16 12:55:26 -07001484void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1485 mLock.unlock();
1486
1487 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1488 if (entry->accuracyChanged) {
1489 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1490 }
1491 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1492 entry->hwTimestamp, entry->values);
1493 mLock.lock();
1494}
1495
1496void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1497 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1498#if DEBUG_OUTBOUND_EVENT_DETAILS
1499 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1500 "source=0x%x, sensorType=%s",
1501 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001502 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001503#endif
1504 std::unique_ptr<CommandEntry> commandEntry =
1505 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1506 commandEntry->sensorEntry = entry;
1507 postCommandLocked(std::move(commandEntry));
1508}
1509
1510bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1511#if DEBUG_OUTBOUND_EVENT_DETAILS
1512 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1513 NamedEnum::string(sensorType).c_str());
1514#endif
1515 { // acquire lock
1516 std::scoped_lock _l(mLock);
1517
1518 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1519 std::shared_ptr<EventEntry> entry = *it;
1520 if (entry->type == EventEntry::Type::SENSOR) {
1521 it = mInboundQueue.erase(it);
1522 releaseInboundEventLocked(entry);
1523 }
1524 }
1525 }
1526 return true;
1527}
1528
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001529bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001530 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001531 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001533 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 entry->dispatchInProgress = true;
1535
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001536 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538
1539 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001540 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001541 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001542 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1543 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 return true;
1545 }
1546
1547 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1548
1549 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001550 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551
1552 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001553 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 if (isPointerEvent) {
1555 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001556 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001557 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 } else {
1560 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001562 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 return false;
1566 }
1567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001568 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001570 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1571 return true;
1572 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001574 CancelationOptions::Mode mode(isPointerEvent
1575 ? CancelationOptions::CANCEL_POINTER_EVENTS
1576 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1577 CancelationOptions options(mode, "input event injection failed");
1578 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 return true;
1580 }
1581
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001582 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001585 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001586 std::unordered_map<int32_t, TouchState>::iterator it =
1587 mTouchStatesByDisplay.find(entry->displayId);
1588 if (it != mTouchStatesByDisplay.end()) {
1589 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001590 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001591 // The event has gone through these portal windows, so we add monitoring targets of
1592 // the corresponding displays as well.
1593 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001594 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001595 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001596 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001597 }
1598 }
1599 }
1600 }
1601
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 // Dispatch the motion.
1603 if (conflictingPointerActions) {
1604 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001605 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 synthesizeCancelationEventsForAllConnectionsLocked(options);
1607 }
1608 dispatchEventLocked(currentTime, entry, inputTargets);
1609 return true;
1610}
1611
arthurhungb89ccb02020-12-30 16:19:01 +08001612void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1613 bool isExiting, const MotionEntry& motionEntry) {
1614 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1615 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1616 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1617 PointerCoords pointerCoords;
1618 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1619 pointerCoords.transform(windowHandle->getInfo()->transform);
1620
1621 std::unique_ptr<DragEntry> dragEntry =
1622 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1623 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1624 pointerCoords.getY());
1625
1626 enqueueInboundEventLocked(std::move(dragEntry));
1627}
1628
1629void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1630 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1631 if (channel == nullptr) {
1632 return; // Window has gone away
1633 }
1634 InputTarget target;
1635 target.inputChannel = channel;
1636 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1637 entry->dispatchInProgress = true;
1638 dispatchEventLocked(currentTime, entry, {target});
1639}
1640
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001641void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001643 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001644 ", policyFlags=0x%x, "
1645 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1646 "metaState=0x%x, buttonState=0x%x,"
1647 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1649 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1650 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001652 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001654 "x=%f, y=%f, pressure=%f, size=%f, "
1655 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1656 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1658 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1659 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1660 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1661 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1662 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1663 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1664 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1665 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1666 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 }
1668#endif
1669}
1670
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001671void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1672 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001674 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675#if DEBUG_DISPATCH_CYCLE
1676 ALOGD("dispatchEventToCurrentInputTargets");
1677#endif
1678
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001679 updateInteractionTokensLocked(*eventEntry, inputTargets);
1680
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1682
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001683 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001685 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001686 sp<Connection> connection =
1687 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001688 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001689 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001691 if (DEBUG_FOCUS) {
1692 ALOGD("Dropping event delivery to target with channel '%s' because it "
1693 "is no longer registered with the input dispatcher.",
1694 inputTarget.inputChannel->getName().c_str());
1695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 }
1697 }
1698}
1699
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001700void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1701 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1702 // If the policy decides to close the app, we will get a channel removal event via
1703 // unregisterInputChannel, and will clean up the connection that way. We are already not
1704 // sending new pointers to the connection when it blocked, but focused events will continue to
1705 // pile up.
1706 ALOGW("Canceling events for %s because it is unresponsive",
1707 connection->inputChannel->getName().c_str());
1708 if (connection->status == Connection::STATUS_NORMAL) {
1709 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1710 "application not responding");
1711 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 }
1713}
1714
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001715void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001716 if (DEBUG_FOCUS) {
1717 ALOGD("Resetting ANR timeouts.");
1718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719
1720 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001721 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001722 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723}
1724
Tiger Huang721e26f2018-07-24 22:26:19 +08001725/**
1726 * Get the display id that the given event should go to. If this event specifies a valid display id,
1727 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1728 * Focused display is the display that the user most recently interacted with.
1729 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001730int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001731 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001732 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001733 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1735 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001736 break;
1737 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001738 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001739 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1740 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 break;
1742 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001743 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001744 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001745 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001746 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001747 case EventEntry::Type::SENSOR:
1748 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001749 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001750 return ADISPLAY_ID_NONE;
1751 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001752 }
1753 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1754}
1755
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001756bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1757 const char* focusedWindowName) {
1758 if (mAnrTracker.empty()) {
1759 // already processed all events that we waited for
1760 mKeyIsWaitingForEventsTimeout = std::nullopt;
1761 return false;
1762 }
1763
1764 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1765 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001766 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001767 mKeyIsWaitingForEventsTimeout = currentTime +
1768 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1769 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001770 return true;
1771 }
1772
1773 // We still have pending events, and already started the timer
1774 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1775 return true; // Still waiting
1776 }
1777
1778 // Waited too long, and some connection still hasn't processed all motions
1779 // Just send the key to the focused window
1780 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1781 focusedWindowName);
1782 mKeyIsWaitingForEventsTimeout = std::nullopt;
1783 return false;
1784}
1785
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1787 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1788 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001789 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790
Tiger Huang721e26f2018-07-24 22:26:19 +08001791 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001792 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001793 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001794 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1795
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 // If there is no currently focused window and no focused application
1797 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001798 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1799 ALOGI("Dropping %s event because there is no focused window or focused application in "
1800 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001801 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001802 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 }
1804
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001805 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1806 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1807 // start interacting with another application via touch (app switch). This code can be removed
1808 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1809 // an app is expected to have a focused window.
1810 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1811 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1812 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001813 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1814 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1815 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001816 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001817 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818 ALOGW("Waiting because no window has focus but %s may eventually add a "
1819 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001820 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001821 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001822 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1824 // Already raised ANR. Drop the event
1825 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001826 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001827 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001828 } else {
1829 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831 }
1832 }
1833
1834 // we have a valid, non-null focused window
1835 resetNoFocusedWindowTimeoutLocked();
1836
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001839 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 }
1841
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001842 if (focusedWindowHandle->getInfo()->paused) {
1843 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001845 }
1846
1847 // If the event is a key event, then we must wait for all previous events to
1848 // complete before delivering it because previous events may have the
1849 // side-effect of transferring focus to a different window and we want to
1850 // ensure that the following keys are sent to the new window.
1851 //
1852 // Suppose the user touches a button in a window then immediately presses "A".
1853 // If the button causes a pop-up window to appear then we want to ensure that
1854 // the "A" key is delivered to the new pop-up window. This is because users
1855 // often anticipate pending UI changes when typing on a keyboard.
1856 // To obtain this behavior, we must serialize key events with respect to all
1857 // prior input events.
1858 if (entry.type == EventEntry::Type::KEY) {
1859 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1860 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001861 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 }
1864
1865 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001866 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001867 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1868 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869
1870 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001871 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872}
1873
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001874/**
1875 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1876 * that are currently unresponsive.
1877 */
1878std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1879 const std::vector<TouchedMonitor>& monitors) const {
1880 std::vector<TouchedMonitor> responsiveMonitors;
1881 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1882 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1883 sp<Connection> connection = getConnectionLocked(
1884 monitor.monitor.inputChannel->getConnectionToken());
1885 if (connection == nullptr) {
1886 ALOGE("Could not find connection for monitor %s",
1887 monitor.monitor.inputChannel->getName().c_str());
1888 return false;
1889 }
1890 if (!connection->responsive) {
1891 ALOGW("Unresponsive monitor %s will not get the new gesture",
1892 connection->inputChannel->getName().c_str());
1893 return false;
1894 }
1895 return true;
1896 });
1897 return responsiveMonitors;
1898}
1899
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001900InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1901 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1902 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001903 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 enum InjectionPermission {
1905 INJECTION_PERMISSION_UNKNOWN,
1906 INJECTION_PERMISSION_GRANTED,
1907 INJECTION_PERMISSION_DENIED
1908 };
1909
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 // For security reasons, we defer updating the touch state until we are sure that
1911 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001912 int32_t displayId = entry.displayId;
1913 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1915
1916 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001919 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1920 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001922 // Copy current touch state into tempTouchState.
1923 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1924 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001925 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001926 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001927 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1928 mTouchStatesByDisplay.find(displayId);
1929 if (oldStateIt != mTouchStatesByDisplay.end()) {
1930 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001931 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001932 }
1933
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001934 bool isSplit = tempTouchState.split;
1935 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1936 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1937 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001938 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1939 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1940 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1941 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1942 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 bool wrongDevice = false;
1945 if (newGesture) {
1946 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001948 ALOGI("Dropping event because a pointer for a different device is already down "
1949 "in display %" PRId32,
1950 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001951 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001952 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 switchedDevice = false;
1954 wrongDevice = true;
1955 goto Failed;
1956 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001957 tempTouchState.reset();
1958 tempTouchState.down = down;
1959 tempTouchState.deviceId = entry.deviceId;
1960 tempTouchState.source = entry.source;
1961 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001963 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001964 ALOGI("Dropping move event because a pointer for a different device is already active "
1965 "in display %" PRId32,
1966 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001967 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001969 switchedDevice = false;
1970 wrongDevice = true;
1971 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 }
1973
1974 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1975 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1976
Garfield Tan00f511d2019-06-12 16:55:40 -07001977 int32_t x;
1978 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001980 // Always dispatch mouse events to cursor position.
1981 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001982 x = int32_t(entry.xCursorPosition);
1983 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001984 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001985 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1986 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001987 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001988 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001989 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001990 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1991 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001992
1993 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001994 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001995 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001998 if (newTouchedWindowHandle != nullptr &&
1999 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002000 // New window supports splitting, but we should never split mouse events.
2001 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 } else if (isSplit) {
2003 // New window does not support splitting but we have already split events.
2004 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002005 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 }
2007
2008 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002009 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002011 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002012 }
2013
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2015 ALOGI("Not sending touch event to %s because it is paused",
2016 newTouchedWindowHandle->getName().c_str());
2017 newTouchedWindowHandle = nullptr;
2018 }
2019
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002020 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002022 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2023 if (!isResponsive) {
2024 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2026 newTouchedWindowHandle = nullptr;
2027 }
2028 }
2029
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002030 // Drop events that can't be trusted due to occlusion
2031 if (newTouchedWindowHandle != nullptr &&
2032 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2033 TouchOcclusionInfo occlusionInfo =
2034 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002035 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002036 if (DEBUG_TOUCH_OCCLUSION) {
2037 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2038 for (const auto& log : occlusionInfo.debugInfo) {
2039 ALOGD("%s", log.c_str());
2040 }
2041 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002042 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2043 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2044 ALOGW("Dropping untrusted touch event due to %s/%d",
2045 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2046 newTouchedWindowHandle = nullptr;
2047 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002048 }
2049 }
2050
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002051 // Also don't send the new touch event to unresponsive gesture monitors
2052 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2053
Michael Wright3dd60e22019-03-27 22:06:44 +00002054 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2055 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056 "(%d, %d) in display %" PRId32 ".",
2057 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002058 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 goto Failed;
2060 }
2061
2062 if (newTouchedWindowHandle != nullptr) {
2063 // Set target flags.
2064 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2065 if (isSplit) {
2066 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002068 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2069 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2070 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2071 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2072 }
2073
2074 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002075 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2076 newHoverWindowHandle = nullptr;
2077 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002078 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002079 }
2080
2081 // Update the temporary touch state.
2082 BitSet32 pointerIds;
2083 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002084 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 pointerIds.markBit(pointerId);
2086 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 }
2089
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002090 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 } else {
2092 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2093
2094 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002096 if (DEBUG_FOCUS) {
2097 ALOGD("Dropping event because the pointer is not down or we previously "
2098 "dropped the pointer down event in display %" PRId32,
2099 displayId);
2100 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002101 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 goto Failed;
2103 }
2104
arthurhung6d4bed92021-03-17 11:59:33 +08002105 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002106
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002108 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002109 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002110 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2111 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112
2113 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002114 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002115 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002116 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2117 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002118 if (DEBUG_FOCUS) {
2119 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2120 oldTouchedWindowHandle->getName().c_str(),
2121 newTouchedWindowHandle->getName().c_str(), displayId);
2122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002124 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2125 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2126 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127
2128 // Make a slippery entrance into the new window.
2129 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2130 isSplit = true;
2131 }
2132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002133 int32_t targetFlags =
2134 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 if (isSplit) {
2136 targetFlags |= InputTarget::FLAG_SPLIT;
2137 }
2138 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2139 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002140 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2141 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 }
2143
2144 BitSet32 pointerIds;
2145 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002146 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002148 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150 }
2151 }
2152
2153 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002154 // Let the previous window know that the hover sequence is over, unless we already did it
2155 // when dispatching it as is to newTouchedWindowHandle.
2156 if (mLastHoverWindowHandle != nullptr &&
2157 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2158 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159#if DEBUG_HOVER
2160 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002161 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002163 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2164 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166
Garfield Tandf26e862020-07-01 20:18:19 -07002167 // Let the new window know that the hover sequence is starting, unless we already did it
2168 // when dispatching it as is to newTouchedWindowHandle.
2169 if (newHoverWindowHandle != nullptr &&
2170 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2171 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172#if DEBUG_HOVER
2173 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2177 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2178 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 }
2180 }
2181
2182 // Check permission to inject into all touched foreground windows and ensure there
2183 // is at least one touched foreground window.
2184 {
2185 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002186 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2188 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002190 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 injectionPermission = INJECTION_PERMISSION_DENIED;
2192 goto Failed;
2193 }
2194 }
2195 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002196 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002197 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002198 ALOGI("Dropping event because there is no touched foreground window in display "
2199 "%" PRId32 " or gesture monitor to receive it.",
2200 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002201 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 goto Failed;
2203 }
2204
2205 // Permission granted to injection into all touched foreground windows.
2206 injectionPermission = INJECTION_PERMISSION_GRANTED;
2207 }
2208
2209 // Check whether windows listening for outside touches are owned by the same UID. If it is
2210 // set the policy flag that we will not reveal coordinate information to this window.
2211 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2212 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002214 if (foregroundWindowHandle) {
2215 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002216 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002217 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2218 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2219 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002220 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2221 InputTarget::FLAG_ZERO_COORDS,
2222 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
2225 }
2226 }
2227 }
2228
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 // If this is the first pointer going down and the touched window has a wallpaper
2230 // then also add the touched wallpaper windows so they are locked in for the duration
2231 // of the touch gesture.
2232 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2233 // engine only supports touch events. We would need to add a mechanism similar
2234 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2235 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2236 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002237 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002238 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002239 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002240 getWindowHandlesLocked(displayId);
2241 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002243 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002244 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002245 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 .addOrUpdateWindow(windowHandle,
2247 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2248 InputTarget::
2249 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2250 InputTarget::FLAG_DISPATCH_AS_IS,
2251 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
2253 }
2254 }
2255 }
2256
2257 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002258 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002260 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002262 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
2264
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002265 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002266 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002268 }
2269
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 // Drop the outside or hover touch windows since we will not care about them
2271 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273
2274Failed:
2275 // Check injection permission once and for all.
2276 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002277 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 injectionPermission = INJECTION_PERMISSION_GRANTED;
2279 } else {
2280 injectionPermission = INJECTION_PERMISSION_DENIED;
2281 }
2282 }
2283
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002284 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2285 return injectionResult;
2286 }
2287
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002289 if (!wrongDevice) {
2290 if (switchedDevice) {
2291 if (DEBUG_FOCUS) {
2292 ALOGD("Conflicting pointer actions: Switched to a different device.");
2293 }
2294 *outConflictingPointerActions = true;
2295 }
2296
2297 if (isHoverAction) {
2298 // Started hovering, therefore no longer down.
2299 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002300 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002301 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2302 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 *outConflictingPointerActions = true;
2305 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002306 tempTouchState.reset();
2307 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2308 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2309 tempTouchState.deviceId = entry.deviceId;
2310 tempTouchState.source = entry.source;
2311 tempTouchState.displayId = displayId;
2312 }
2313 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2314 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2315 // All pointers up or canceled.
2316 tempTouchState.reset();
2317 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2318 // First pointer went down.
2319 if (oldState && oldState->down) {
2320 if (DEBUG_FOCUS) {
2321 ALOGD("Conflicting pointer actions: Down received while already down.");
2322 }
2323 *outConflictingPointerActions = true;
2324 }
2325 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2326 // One pointer went up.
2327 if (isSplit) {
2328 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2329 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002331 for (size_t i = 0; i < tempTouchState.windows.size();) {
2332 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2333 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2334 touchedWindow.pointerIds.clearBit(pointerId);
2335 if (touchedWindow.pointerIds.isEmpty()) {
2336 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2337 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002340 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002342 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002343 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002344
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002345 // Save changes unless the action was scroll in which case the temporary touch
2346 // state was only valid for this one action.
2347 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2348 if (tempTouchState.displayId >= 0) {
2349 mTouchStatesByDisplay[displayId] = tempTouchState;
2350 } else {
2351 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002355 // Update hover state.
2356 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
2358
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 return injectionResult;
2360}
2361
arthurhung6d4bed92021-03-17 11:59:33 +08002362void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2363 const sp<InputWindowHandle> dropWindow =
2364 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2365 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2366 true /*ignoreDragWindow*/);
2367 if (dropWindow) {
2368 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2369 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002370 } else {
2371 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002372 }
2373 mDragState.reset();
2374}
2375
2376void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2377 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002378 return;
2379 }
2380
arthurhung6d4bed92021-03-17 11:59:33 +08002381 if (!mDragState->isStartDrag) {
2382 mDragState->isStartDrag = true;
2383 mDragState->isStylusButtonDownAtStart =
2384 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2385 }
2386
arthurhungb89ccb02020-12-30 16:19:01 +08002387 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2388 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2389 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2390 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002391 // Handle the special case : stylus button no longer pressed.
2392 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2393 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2394 finishDragAndDrop(entry.displayId, x, y);
2395 return;
2396 }
2397
arthurhungb89ccb02020-12-30 16:19:01 +08002398 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002399 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002400 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2401 true /*ignoreDragWindow*/);
2402 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002403 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2404 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2405 if (mDragState->dragHoverWindowHandle != nullptr) {
2406 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2407 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002408 }
arthurhung6d4bed92021-03-17 11:59:33 +08002409 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002410 }
2411 // enqueue drag location if needed.
2412 if (hoverWindowHandle != nullptr) {
2413 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2414 }
arthurhung6d4bed92021-03-17 11:59:33 +08002415 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2416 finishDragAndDrop(entry.displayId, x, y);
2417 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002418 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002419 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002420 }
2421}
2422
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002424 int32_t targetFlags, BitSet32 pointerIds,
2425 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002426 std::vector<InputTarget>::iterator it =
2427 std::find_if(inputTargets.begin(), inputTargets.end(),
2428 [&windowHandle](const InputTarget& inputTarget) {
2429 return inputTarget.inputChannel->getConnectionToken() ==
2430 windowHandle->getToken();
2431 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002432
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002433 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002434
2435 if (it == inputTargets.end()) {
2436 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002437 std::shared_ptr<InputChannel> inputChannel =
2438 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439 if (inputChannel == nullptr) {
2440 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2441 return;
2442 }
2443 inputTarget.inputChannel = inputChannel;
2444 inputTarget.flags = targetFlags;
2445 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002446 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002447 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002448 inputTargets.push_back(inputTarget);
2449 it = inputTargets.end() - 1;
2450 }
2451
2452 ALOG_ASSERT(it->flags == targetFlags);
2453 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2454
chaviw1ff3d1e2020-07-01 15:53:47 -07002455 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456}
2457
Michael Wright3dd60e22019-03-27 22:06:44 +00002458void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459 int32_t displayId, float xOffset,
2460 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002461 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2462 mGlobalMonitorsByDisplay.find(displayId);
2463
2464 if (it != mGlobalMonitorsByDisplay.end()) {
2465 const std::vector<Monitor>& monitors = it->second;
2466 for (const Monitor& monitor : monitors) {
2467 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470}
2471
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002472void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2473 float yOffset,
2474 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002475 InputTarget target;
2476 target.inputChannel = monitor.inputChannel;
2477 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002478 ui::Transform t;
2479 t.set(xOffset, yOffset);
2480 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002481 inputTargets.push_back(target);
2482}
2483
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 const InjectionState* injectionState) {
2486 if (injectionState &&
2487 (windowHandle == nullptr ||
2488 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2489 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002490 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002492 "owned by uid %d",
2493 injectionState->injectorPid, injectionState->injectorUid,
2494 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 } else {
2496 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 }
2499 return false;
2500 }
2501 return true;
2502}
2503
Robert Carrc9bf1d32020-04-13 17:21:08 -07002504/**
2505 * Indicate whether one window handle should be considered as obscuring
2506 * another window handle. We only check a few preconditions. Actually
2507 * checking the bounds is left to the caller.
2508 */
2509static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2510 const sp<InputWindowHandle>& otherHandle) {
2511 // Compare by token so cloned layers aren't counted
2512 if (haveSameToken(windowHandle, otherHandle)) {
2513 return false;
2514 }
2515 auto info = windowHandle->getInfo();
2516 auto otherInfo = otherHandle->getInfo();
2517 if (!otherInfo->visible) {
2518 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002519 } else if (otherInfo->alpha == 0 &&
2520 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2521 // Those act as if they were invisible, so we don't need to flag them.
2522 // We do want to potentially flag touchable windows even if they have 0
2523 // opacity, since they can consume touches and alter the effects of the
2524 // user interaction (eg. apps that rely on
2525 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2526 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2527 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002528 } else if (info->ownerUid == otherInfo->ownerUid) {
2529 // If ownerUid is the same we don't generate occlusion events as there
2530 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002531 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002532 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002533 return false;
2534 } else if (otherInfo->displayId != info->displayId) {
2535 return false;
2536 }
2537 return true;
2538}
2539
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002540/**
2541 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2542 * untrusted, one should check:
2543 *
2544 * 1. If result.hasBlockingOcclusion is true.
2545 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2546 * BLOCK_UNTRUSTED.
2547 *
2548 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2549 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2550 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2551 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2552 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2553 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2554 *
2555 * If neither of those is true, then it means the touch can be allowed.
2556 */
2557InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2558 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002559 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2560 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002561 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2562 TouchOcclusionInfo info;
2563 info.hasBlockingOcclusion = false;
2564 info.obscuringOpacity = 0;
2565 info.obscuringUid = -1;
2566 std::map<int32_t, float> opacityByUid;
2567 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2568 if (windowHandle == otherHandle) {
2569 break; // All future windows are below us. Exit early.
2570 }
2571 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002572 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2573 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002574 if (DEBUG_TOUCH_OCCLUSION) {
2575 info.debugInfo.push_back(
2576 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2577 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002578 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2579 // we perform the checks below to see if the touch can be propagated or not based on the
2580 // window's touch occlusion mode
2581 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2582 info.hasBlockingOcclusion = true;
2583 info.obscuringUid = otherInfo->ownerUid;
2584 info.obscuringPackage = otherInfo->packageName;
2585 break;
2586 }
2587 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2588 uint32_t uid = otherInfo->ownerUid;
2589 float opacity =
2590 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2591 // Given windows A and B:
2592 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2593 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2594 opacityByUid[uid] = opacity;
2595 if (opacity > info.obscuringOpacity) {
2596 info.obscuringOpacity = opacity;
2597 info.obscuringUid = uid;
2598 info.obscuringPackage = otherInfo->packageName;
2599 }
2600 }
2601 }
2602 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002603 if (DEBUG_TOUCH_OCCLUSION) {
2604 info.debugInfo.push_back(
2605 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2606 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002607 return info;
2608}
2609
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002610std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2611 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002612 return StringPrintf(INDENT2
2613 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2614 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2615 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2616 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002617 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002618 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002619 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002620 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2621 info->frameTop, info->frameRight, info->frameBottom,
2622 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002623 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2624 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2625 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002626}
2627
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002628bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2629 if (occlusionInfo.hasBlockingOcclusion) {
2630 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2631 occlusionInfo.obscuringUid);
2632 return false;
2633 }
2634 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2635 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2636 "%.2f, maximum allowed = %.2f)",
2637 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2638 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2639 return false;
2640 }
2641 return true;
2642}
2643
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2645 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002647 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002648 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002649 if (windowHandle == otherHandle) {
2650 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002653 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002654 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 return true;
2656 }
2657 }
2658 return false;
2659}
2660
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002661bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2662 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002663 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002664 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002665 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002666 if (windowHandle == otherHandle) {
2667 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002668 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002669 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002670 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002671 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002672 return true;
2673 }
2674 }
2675 return false;
2676}
2677
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002678std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002679 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002681 if (applicationHandle != nullptr) {
2682 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002683 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 } else {
2685 return applicationHandle->getName();
2686 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002687 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002688 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002690 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 }
2692}
2693
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002694void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002695 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002696 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2697 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002698 // Focus or pointer capture changed events are passed to apps, but do not represent user
2699 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002700 return;
2701 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002702 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002703 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002704 if (focusedWindowHandle != nullptr) {
2705 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002706 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002708 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709#endif
2710 return;
2711 }
2712 }
2713
2714 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002715 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002716 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002717 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2718 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 return;
2720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002722 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 eventType = USER_ACTIVITY_EVENT_TOUCH;
2724 }
2725 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002727 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002728 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2729 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 return;
2731 }
2732 eventType = USER_ACTIVITY_EVENT_BUTTON;
2733 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002735 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002736 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002737 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002738 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002739 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2740 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002741 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002742 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002743 break;
2744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 }
2746
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002747 std::unique_ptr<CommandEntry> commandEntry =
2748 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002749 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002751 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002752 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753}
2754
2755void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002756 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002757 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002758 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002759 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002761 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002762 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002763 ATRACE_NAME(message.c_str());
2764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765#if DEBUG_DISPATCH_CYCLE
2766 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002767 "globalScaleFactor=%f, pointerIds=0x%x %s",
2768 connection->getInputChannelName().c_str(), inputTarget.flags,
2769 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2770 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771#endif
2772
2773 // Skip this event if the connection status is not normal.
2774 // We don't want to enqueue additional outbound events if the connection is broken.
2775 if (connection->status != Connection::STATUS_NORMAL) {
2776#if DEBUG_DISPATCH_CYCLE
2777 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779#endif
2780 return;
2781 }
2782
2783 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002784 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2785 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2786 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002787 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002789 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002790 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002791 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002792 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 if (!splitMotionEntry) {
2794 return; // split event was dropped
2795 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002796 if (DEBUG_FOCUS) {
2797 ALOGD("channel '%s' ~ Split motion event.",
2798 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002799 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002800 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002801 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2802 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 return;
2804 }
2805 }
2806
2807 // Not splitting. Enqueue dispatch entries for the event as is.
2808 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2809}
2810
2811void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002813 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002814 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002815 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002816 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002817 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002818 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002819 ATRACE_NAME(message.c_str());
2820 }
2821
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002822 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823
2824 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002825 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002826 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002829 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002831 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002833 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002835 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
2838 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002839 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 startDispatchCycleLocked(currentTime, connection);
2841 }
2842}
2843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002845 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002846 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002848 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2850 connection->getInputChannelName().c_str(),
2851 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002852 ATRACE_NAME(message.c_str());
2853 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002854 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 if (!(inputTargetFlags & dispatchMode)) {
2856 return;
2857 }
2858 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2859
2860 // This is a new event.
2861 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002862 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002863 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002865 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2866 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002867 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002869 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002870 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002871 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002872 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002873 dispatchEntry->resolvedAction = keyEntry.action;
2874 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002876 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2877 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2880 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 return; // skip the inconsistent event
2883 }
2884 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002887 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002888 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002889 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2890 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2891 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2892 static_cast<int32_t>(IdGenerator::Source::OTHER);
2893 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2895 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2896 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2897 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2898 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2899 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2900 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2901 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2902 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2903 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2904 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002905 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002906 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002907 }
2908 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002909 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2910 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2913 "event",
2914 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002916 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2917 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002921 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002922 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2923 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2924 }
2925 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2926 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2930 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2933 "event",
2934 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 return; // skip the inconsistent event
2937 }
2938
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002939 dispatchEntry->resolvedEventId =
2940 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2941 ? mIdGenerator.nextId()
2942 : motionEntry.id;
2943 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2944 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2945 ") to MotionEvent(id=0x%" PRIx32 ").",
2946 motionEntry.id, dispatchEntry->resolvedEventId);
2947 ATRACE_NAME(message.c_str());
2948 }
2949
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002950 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2951 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2952 // Skip reporting pointer down outside focus to the policy.
2953 break;
2954 }
2955
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002956 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002957 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958
2959 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002961 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002962 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2963 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002964 break;
2965 }
Chris Yef59a2f42020-10-16 12:55:26 -07002966 case EventEntry::Type::SENSOR: {
2967 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2968 break;
2969 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002970 case EventEntry::Type::CONFIGURATION_CHANGED:
2971 case EventEntry::Type::DEVICE_RESET: {
2972 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002973 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002974 break;
2975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 }
2977
2978 // Remember that we are waiting for this dispatch to complete.
2979 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002980 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981 }
2982
2983 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002984 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002985 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002986}
2987
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002988/**
2989 * This function is purely for debugging. It helps us understand where the user interaction
2990 * was taking place. For example, if user is touching launcher, we will see a log that user
2991 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2992 * We will see both launcher and wallpaper in that list.
2993 * Once the interaction with a particular set of connections starts, no new logs will be printed
2994 * until the set of interacted connections changes.
2995 *
2996 * The following items are skipped, to reduce the logspam:
2997 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2998 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2999 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3000 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3001 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003002 */
3003void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3004 const std::vector<InputTarget>& targets) {
3005 // Skip ACTION_UP events, and all events other than keys and motions
3006 if (entry.type == EventEntry::Type::KEY) {
3007 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3008 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3009 return;
3010 }
3011 } else if (entry.type == EventEntry::Type::MOTION) {
3012 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3013 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3014 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3015 return;
3016 }
3017 } else {
3018 return; // Not a key or a motion
3019 }
3020
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003021 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003022 std::vector<sp<Connection>> newConnections;
3023 for (const InputTarget& target : targets) {
3024 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3025 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3026 continue; // Skip windows that receive ACTION_OUTSIDE
3027 }
3028
3029 sp<IBinder> token = target.inputChannel->getConnectionToken();
3030 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003031 if (connection == nullptr) {
3032 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003033 }
3034 newConnectionTokens.insert(std::move(token));
3035 newConnections.emplace_back(connection);
3036 }
3037 if (newConnectionTokens == mInteractionConnectionTokens) {
3038 return; // no change
3039 }
3040 mInteractionConnectionTokens = newConnectionTokens;
3041
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003042 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003043 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003044 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003045 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003046 std::string message = "Interaction with: " + targetList;
3047 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003048 message += "<none>";
3049 }
3050 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3051}
3052
chaviwfd6d3512019-03-25 13:23:49 -07003053void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003054 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003055 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003056 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3057 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003058 return;
3059 }
3060
Vishnu Nairc519ff72021-01-21 08:23:08 -08003061 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003062 if (focusedToken == token) {
3063 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003064 return;
3065 }
3066
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003067 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3068 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003069 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003070 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071}
3072
3073void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003075 if (ATRACE_ENABLED()) {
3076 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003078 ATRACE_NAME(message.c_str());
3079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082#endif
3083
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003084 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3085 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003087 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003088 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003089 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090
3091 // Publish the event.
3092 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003093 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3094 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003095 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003096 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3097 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003100 status = connection->inputPublisher
3101 .publishKeyEvent(dispatchEntry->seq,
3102 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3103 keyEntry.source, keyEntry.displayId,
3104 std::move(hmac), dispatchEntry->resolvedAction,
3105 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3106 keyEntry.scanCode, keyEntry.metaState,
3107 keyEntry.repeatCount, keyEntry.downTime,
3108 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 }
3111
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003112 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003113 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003115 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003116 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117
chaviw82357092020-01-28 13:13:06 -08003118 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003119 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3121 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003122 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003123 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3124 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003125 // Don't apply window scale here since we don't want scale to affect raw
3126 // coordinates. The scale will be sent back to the client and applied
3127 // later when requesting relative coordinates.
3128 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3129 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003130 }
3131 usingCoords = scaledCoords;
3132 }
3133 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 // We don't want the dispatch target to know.
3135 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003136 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 scaledCoords[i].clear();
3138 }
3139 usingCoords = scaledCoords;
3140 }
3141 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003142
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003143 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144
3145 // Publish the motion event.
3146 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003147 .publishMotionEvent(dispatchEntry->seq,
3148 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003149 motionEntry.deviceId, motionEntry.source,
3150 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003151 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003152 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003153 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003154 motionEntry.edgeFlags, motionEntry.metaState,
3155 motionEntry.buttonState,
3156 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003157 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003158 motionEntry.xPrecision, motionEntry.yPrecision,
3159 motionEntry.xCursorPosition,
3160 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003161 dispatchEntry->displaySize.x,
3162 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 motionEntry.downTime, motionEntry.eventTime,
3164 motionEntry.pointerCount,
3165 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003166 break;
3167 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003168
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003169 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003170 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003171 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003172 focusEntry.id,
3173 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003174 mInTouchMode);
3175 break;
3176 }
3177
Prabir Pradhan99987712020-11-10 18:43:05 -08003178 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3179 const auto& captureEntry =
3180 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3181 status = connection->inputPublisher
3182 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3183 captureEntry.pointerCaptureEnabled);
3184 break;
3185 }
3186
arthurhungb89ccb02020-12-30 16:19:01 +08003187 case EventEntry::Type::DRAG: {
3188 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3189 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3190 dragEntry.id, dragEntry.x,
3191 dragEntry.y,
3192 dragEntry.isExiting);
3193 break;
3194 }
3195
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003196 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003197 case EventEntry::Type::DEVICE_RESET:
3198 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003199 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003200 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
3204
3205 // Check the result.
3206 if (status) {
3207 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003208 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003210 "This is unexpected because the wait queue is empty, so the pipe "
3211 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003212 "event to it, status=%s(%d)",
3213 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3214 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3216 } else {
3217 // Pipe is full and we are waiting for the app to finish process some events
3218 // before sending more events to it.
3219#if DEBUG_DISPATCH_CYCLE
3220 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 "waiting for the application to catch up",
3222 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 }
3225 } else {
3226 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003227 "status=%s(%d)",
3228 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3229 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3231 }
3232 return;
3233 }
3234
3235 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003236 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3237 connection->outboundQueue.end(),
3238 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003239 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003240 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003241 if (connection->responsive) {
3242 mAnrTracker.insert(dispatchEntry->timeoutTime,
3243 connection->inputChannel->getConnectionToken());
3244 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003245 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
3247}
3248
chaviw09c8d2d2020-08-24 15:48:26 -07003249std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3250 size_t size;
3251 switch (event.type) {
3252 case VerifiedInputEvent::Type::KEY: {
3253 size = sizeof(VerifiedKeyEvent);
3254 break;
3255 }
3256 case VerifiedInputEvent::Type::MOTION: {
3257 size = sizeof(VerifiedMotionEvent);
3258 break;
3259 }
3260 }
3261 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3262 return mHmacKeyManager.sign(start, size);
3263}
3264
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003265const std::array<uint8_t, 32> InputDispatcher::getSignature(
3266 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3267 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3268 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3269 // Only sign events up and down events as the purely move events
3270 // are tied to their up/down counterparts so signing would be redundant.
3271 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3272 verifiedEvent.actionMasked = actionMasked;
3273 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003274 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003275 }
3276 return INVALID_HMAC;
3277}
3278
3279const std::array<uint8_t, 32> InputDispatcher::getSignature(
3280 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3281 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3282 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3283 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003284 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003285}
3286
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003289 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290#if DEBUG_DISPATCH_CYCLE
3291 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293#endif
3294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 if (connection->status == Connection::STATUS_BROKEN ||
3296 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 return;
3298 }
3299
3300 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003301 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302}
3303
3304void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 const sp<Connection>& connection,
3306 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307#if DEBUG_DISPATCH_CYCLE
3308 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310#endif
3311
3312 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003313 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003314 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003315 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003316 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
3318 // The connection appears to be unrecoverably broken.
3319 // Ignore already broken or zombie connections.
3320 if (connection->status == Connection::STATUS_NORMAL) {
3321 connection->status = Connection::STATUS_BROKEN;
3322
3323 if (notify) {
3324 // Notify other system components.
3325 onDispatchCycleBrokenLocked(currentTime, connection);
3326 }
3327 }
3328}
3329
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003330void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3331 while (!queue.empty()) {
3332 DispatchEntry* dispatchEntry = queue.front();
3333 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003334 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
3336}
3337
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003338void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003340 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 }
3342 delete dispatchEntry;
3343}
3344
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003345int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3346 std::scoped_lock _l(mLock);
3347 sp<Connection> connection = getConnectionLocked(connectionToken);
3348 if (connection == nullptr) {
3349 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3350 connectionToken.get(), events);
3351 return 0; // remove the callback
3352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003354 bool notify;
3355 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3356 if (!(events & ALOOPER_EVENT_INPUT)) {
3357 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3358 "events=0x%x",
3359 connection->getInputChannelName().c_str(), events);
3360 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 }
3362
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003363 nsecs_t currentTime = now();
3364 bool gotOne = false;
3365 status_t status = OK;
3366 for (;;) {
3367 Result<InputPublisher::ConsumerResponse> result =
3368 connection->inputPublisher.receiveConsumerResponse();
3369 if (!result.ok()) {
3370 status = result.error().code();
3371 break;
3372 }
3373
3374 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3375 const InputPublisher::Finished& finish =
3376 std::get<InputPublisher::Finished>(*result);
3377 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3378 finish.consumeTime);
3379 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003380 if (shouldReportMetricsForConnection(*connection)) {
3381 const InputPublisher::Timeline& timeline =
3382 std::get<InputPublisher::Timeline>(*result);
3383 mLatencyTracker
3384 .trackGraphicsLatency(timeline.inputEventId,
3385 connection->inputChannel->getConnectionToken(),
3386 std::move(timeline.graphicsTimeline));
3387 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003388 }
3389 gotOne = true;
3390 }
3391 if (gotOne) {
3392 runCommandsLockedInterruptible();
3393 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 return 1;
3395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 }
3397
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003398 notify = status != DEAD_OBJECT || !connection->monitor;
3399 if (notify) {
3400 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3401 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3402 status);
3403 }
3404 } else {
3405 // Monitor channels are never explicitly unregistered.
3406 // We do it automatically when the remote endpoint is closed so don't warn about them.
3407 const bool stillHaveWindowHandle =
3408 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3409 notify = !connection->monitor && stillHaveWindowHandle;
3410 if (notify) {
3411 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3412 connection->getInputChannelName().c_str(), events);
3413 }
3414 }
3415
3416 // Remove the channel.
3417 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3418 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419}
3420
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003421void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003423 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003424 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426}
3427
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003429 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003430 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3431 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3432}
3433
3434void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3435 const CancelationOptions& options,
3436 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3437 for (const auto& it : monitorsByDisplay) {
3438 const std::vector<Monitor>& monitors = it.second;
3439 for (const Monitor& monitor : monitors) {
3440 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003441 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003442 }
3443}
3444
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003446 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003447 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003448 if (connection == nullptr) {
3449 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003451
3452 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453}
3454
3455void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3456 const sp<Connection>& connection, const CancelationOptions& options) {
3457 if (connection->status == Connection::STATUS_BROKEN) {
3458 return;
3459 }
3460
3461 nsecs_t currentTime = now();
3462
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003463 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003464 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003466 if (cancelationEvents.empty()) {
3467 return;
3468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003470 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3471 "with reality: %s, mode=%d.",
3472 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3473 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003475
3476 InputTarget target;
3477 sp<InputWindowHandle> windowHandle =
3478 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3479 if (windowHandle != nullptr) {
3480 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003481 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003482 target.globalScaleFactor = windowInfo->globalScaleFactor;
3483 }
3484 target.inputChannel = connection->inputChannel;
3485 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3486
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003487 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003488 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003489 switch (cancelationEventEntry->type) {
3490 case EventEntry::Type::KEY: {
3491 logOutboundKeyDetails("cancel - ",
3492 static_cast<const KeyEntry&>(*cancelationEventEntry));
3493 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003495 case EventEntry::Type::MOTION: {
3496 logOutboundMotionDetails("cancel - ",
3497 static_cast<const MotionEntry&>(*cancelationEventEntry));
3498 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003500 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003501 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3502 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003503 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003504 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003505 break;
3506 }
3507 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003508 case EventEntry::Type::DEVICE_RESET:
3509 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003510 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003511 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003512 break;
3513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 }
3515
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003516 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3517 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003519
3520 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521}
3522
Svet Ganov5d3bc372020-01-26 23:11:07 -08003523void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3524 const sp<Connection>& connection) {
3525 if (connection->status == Connection::STATUS_BROKEN) {
3526 return;
3527 }
3528
3529 nsecs_t currentTime = now();
3530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003531 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003532 connection->inputState.synthesizePointerDownEvents(currentTime);
3533
3534 if (downEvents.empty()) {
3535 return;
3536 }
3537
3538#if DEBUG_OUTBOUND_EVENT_DETAILS
3539 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3540 connection->getInputChannelName().c_str(), downEvents.size());
3541#endif
3542
3543 InputTarget target;
3544 sp<InputWindowHandle> windowHandle =
3545 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3546 if (windowHandle != nullptr) {
3547 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003548 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003549 target.globalScaleFactor = windowInfo->globalScaleFactor;
3550 }
3551 target.inputChannel = connection->inputChannel;
3552 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3553
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003554 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003555 switch (downEventEntry->type) {
3556 case EventEntry::Type::MOTION: {
3557 logOutboundMotionDetails("down - ",
3558 static_cast<const MotionEntry&>(*downEventEntry));
3559 break;
3560 }
3561
3562 case EventEntry::Type::KEY:
3563 case EventEntry::Type::FOCUS:
3564 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003565 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003566 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003567 case EventEntry::Type::SENSOR:
3568 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003569 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003570 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003571 break;
3572 }
3573 }
3574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003575 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3576 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003577 }
3578
3579 startDispatchCycleLocked(currentTime, connection);
3580}
3581
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003582std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3583 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 ALOG_ASSERT(pointerIds.value != 0);
3585
3586 uint32_t splitPointerIndexMap[MAX_POINTERS];
3587 PointerProperties splitPointerProperties[MAX_POINTERS];
3588 PointerCoords splitPointerCoords[MAX_POINTERS];
3589
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003590 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 uint32_t splitPointerCount = 0;
3592
3593 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003594 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003596 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 uint32_t pointerId = uint32_t(pointerProperties.id);
3598 if (pointerIds.hasBit(pointerId)) {
3599 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3600 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3601 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003602 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 splitPointerCount += 1;
3604 }
3605 }
3606
3607 if (splitPointerCount != pointerIds.count()) {
3608 // This is bad. We are missing some of the pointers that we expected to deliver.
3609 // Most likely this indicates that we received an ACTION_MOVE events that has
3610 // different pointer ids than we expected based on the previous ACTION_DOWN
3611 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3612 // in this way.
3613 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 "we expected there to be %d pointers. This probably means we received "
3615 "a broken sequence of pointer ids from the input device.",
3616 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003617 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003620 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003622 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3623 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3625 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003626 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 uint32_t pointerId = uint32_t(pointerProperties.id);
3628 if (pointerIds.hasBit(pointerId)) {
3629 if (pointerIds.count() == 1) {
3630 // The first/last pointer went down/up.
3631 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003632 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003633 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3634 ? AMOTION_EVENT_ACTION_CANCEL
3635 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 } else {
3637 // A secondary pointer went down/up.
3638 uint32_t splitPointerIndex = 0;
3639 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3640 splitPointerIndex += 1;
3641 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003642 action = maskedAction |
3643 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 }
3645 } else {
3646 // An unrelated pointer changed.
3647 action = AMOTION_EVENT_ACTION_MOVE;
3648 }
3649 }
3650
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003651 int32_t newId = mIdGenerator.nextId();
3652 if (ATRACE_ENABLED()) {
3653 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3654 ") to MotionEvent(id=0x%" PRIx32 ").",
3655 originalMotionEntry.id, newId);
3656 ATRACE_NAME(message.c_str());
3657 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003658 std::unique_ptr<MotionEntry> splitMotionEntry =
3659 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3660 originalMotionEntry.deviceId, originalMotionEntry.source,
3661 originalMotionEntry.displayId,
3662 originalMotionEntry.policyFlags, action,
3663 originalMotionEntry.actionButton,
3664 originalMotionEntry.flags, originalMotionEntry.metaState,
3665 originalMotionEntry.buttonState,
3666 originalMotionEntry.classification,
3667 originalMotionEntry.edgeFlags,
3668 originalMotionEntry.xPrecision,
3669 originalMotionEntry.yPrecision,
3670 originalMotionEntry.xCursorPosition,
3671 originalMotionEntry.yCursorPosition,
3672 originalMotionEntry.downTime, splitPointerCount,
3673 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003675 if (originalMotionEntry.injectionState) {
3676 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 splitMotionEntry->injectionState->refCount += 1;
3678 }
3679
3680 return splitMotionEntry;
3681}
3682
3683void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3684#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003685 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686#endif
3687
3688 bool needWake;
3689 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003690 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003692 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3693 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3694 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 } // release lock
3696
3697 if (needWake) {
3698 mLooper->wake();
3699 }
3700}
3701
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003702/**
3703 * If one of the meta shortcuts is detected, process them here:
3704 * Meta + Backspace -> generate BACK
3705 * Meta + Enter -> generate HOME
3706 * This will potentially overwrite keyCode and metaState.
3707 */
3708void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003709 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003710 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3711 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3712 if (keyCode == AKEYCODE_DEL) {
3713 newKeyCode = AKEYCODE_BACK;
3714 } else if (keyCode == AKEYCODE_ENTER) {
3715 newKeyCode = AKEYCODE_HOME;
3716 }
3717 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003718 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003719 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003720 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003721 keyCode = newKeyCode;
3722 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3723 }
3724 } else if (action == AKEY_EVENT_ACTION_UP) {
3725 // In order to maintain a consistent stream of up and down events, check to see if the key
3726 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3727 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003728 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003729 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003730 auto replacementIt = mReplacedKeys.find(replacement);
3731 if (replacementIt != mReplacedKeys.end()) {
3732 keyCode = replacementIt->second;
3733 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003734 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3735 }
3736 }
3737}
3738
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3740#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3742 "policyFlags=0x%x, action=0x%x, "
3743 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3744 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3745 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3746 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747#endif
3748 if (!validateKeyEvent(args->action)) {
3749 return;
3750 }
3751
3752 uint32_t policyFlags = args->policyFlags;
3753 int32_t flags = args->flags;
3754 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003755 // InputDispatcher tracks and generates key repeats on behalf of
3756 // whatever notifies it, so repeatCount should always be set to 0
3757 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3759 policyFlags |= POLICY_FLAG_VIRTUAL;
3760 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 if (policyFlags & POLICY_FLAG_FUNCTION) {
3763 metaState |= AMETA_FUNCTION_ON;
3764 }
3765
3766 policyFlags |= POLICY_FLAG_TRUSTED;
3767
Michael Wright78f24442014-08-06 15:55:28 -07003768 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003769 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003770
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003772 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003773 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3774 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775
Michael Wright2b3c3302018-03-02 17:19:13 +00003776 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003778 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3779 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003780 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 bool needWake;
3784 { // acquire lock
3785 mLock.lock();
3786
3787 if (shouldSendKeyToInputFilterLocked(args)) {
3788 mLock.unlock();
3789
3790 policyFlags |= POLICY_FLAG_FILTERED;
3791 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3792 return; // event was consumed by the filter
3793 }
3794
3795 mLock.lock();
3796 }
3797
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003798 std::unique_ptr<KeyEntry> newEntry =
3799 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3800 args->displayId, policyFlags, args->action, flags,
3801 keyCode, args->scanCode, metaState, repeatCount,
3802 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003804 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 mLock.unlock();
3806 } // release lock
3807
3808 if (needWake) {
3809 mLooper->wake();
3810 }
3811}
3812
3813bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3814 return mInputFilterEnabled;
3815}
3816
3817void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3818#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003819 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3820 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003821 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3822 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003823 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003824 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3825 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3826 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3827 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 for (uint32_t i = 0; i < args->pointerCount; i++) {
3829 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 "x=%f, y=%f, pressure=%f, size=%f, "
3831 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3832 "orientation=%f",
3833 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3834 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3835 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3836 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3837 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3838 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3839 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3840 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3841 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3842 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 }
3844#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003845 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3846 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 return;
3848 }
3849
3850 uint32_t policyFlags = args->policyFlags;
3851 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003852
3853 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003854 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003855 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3856 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003857 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859
3860 bool needWake;
3861 { // acquire lock
3862 mLock.lock();
3863
3864 if (shouldSendMotionToInputFilterLocked(args)) {
3865 mLock.unlock();
3866
3867 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003868 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003869 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3870 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003871 args->metaState, args->buttonState, args->classification, transform,
3872 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003873 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3874 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003875 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876
3877 policyFlags |= POLICY_FLAG_FILTERED;
3878 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3879 return; // event was consumed by the filter
3880 }
3881
3882 mLock.lock();
3883 }
3884
3885 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003886 std::unique_ptr<MotionEntry> newEntry =
3887 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3888 args->source, args->displayId, policyFlags,
3889 args->action, args->actionButton, args->flags,
3890 args->metaState, args->buttonState,
3891 args->classification, args->edgeFlags,
3892 args->xPrecision, args->yPrecision,
3893 args->xCursorPosition, args->yCursorPosition,
3894 args->downTime, args->pointerCount,
3895 args->pointerProperties, args->pointerCoords, 0, 0);
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003896 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3897 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3898 !mInputFilterEnabled) {
3899 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3900 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003903 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 mLock.unlock();
3905 } // release lock
3906
3907 if (needWake) {
3908 mLooper->wake();
3909 }
3910}
3911
Chris Yef59a2f42020-10-16 12:55:26 -07003912void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3913#if DEBUG_INBOUND_EVENT_DETAILS
3914 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3915 " sensorType=%s",
3916 args->id, args->eventTime, args->deviceId, args->source,
3917 NamedEnum::string(args->sensorType).c_str());
3918#endif
3919
3920 bool needWake;
3921 { // acquire lock
3922 mLock.lock();
3923
3924 // Just enqueue a new sensor event.
3925 std::unique_ptr<SensorEntry> newEntry =
3926 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3927 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3928 args->sensorType, args->accuracy,
3929 args->accuracyChanged, args->values);
3930
3931 needWake = enqueueInboundEventLocked(std::move(newEntry));
3932 mLock.unlock();
3933 } // release lock
3934
3935 if (needWake) {
3936 mLooper->wake();
3937 }
3938}
3939
Chris Yefb552902021-02-03 17:18:37 -08003940void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3941#if DEBUG_INBOUND_EVENT_DETAILS
3942 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3943 args->deviceId, args->isOn);
3944#endif
3945 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3946}
3947
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003949 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950}
3951
3952void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3953#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003954 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003955 "switchMask=0x%08x",
3956 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957#endif
3958
3959 uint32_t policyFlags = args->policyFlags;
3960 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003961 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962}
3963
3964void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3965#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003966 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3967 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968#endif
3969
3970 bool needWake;
3971 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003972 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003974 std::unique_ptr<DeviceResetEntry> newEntry =
3975 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3976 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 } // release lock
3978
3979 if (needWake) {
3980 mLooper->wake();
3981 }
3982}
3983
Prabir Pradhan7e186182020-11-10 13:56:45 -08003984void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3985#if DEBUG_INBOUND_EVENT_DETAILS
3986 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3987 args->enabled ? "true" : "false");
3988#endif
3989
Prabir Pradhan99987712020-11-10 18:43:05 -08003990 bool needWake;
3991 { // acquire lock
3992 std::scoped_lock _l(mLock);
3993 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3994 args->enabled);
3995 needWake = enqueueInboundEventLocked(std::move(entry));
3996 } // release lock
3997
3998 if (needWake) {
3999 mLooper->wake();
4000 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004001}
4002
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004003InputEventInjectionResult InputDispatcher::injectInputEvent(
4004 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4005 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006#if DEBUG_INBOUND_EVENT_DETAILS
4007 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004008 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4009 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004011 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012
4013 policyFlags |= POLICY_FLAG_INJECTED;
4014 if (hasInjectionPermission(injectorPid, injectorUid)) {
4015 policyFlags |= POLICY_FLAG_TRUSTED;
4016 }
4017
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004018 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004020 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004021 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4022 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004023 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004024 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004027 int32_t flags = incomingKey.getFlags();
4028 int32_t keyCode = incomingKey.getKeyCode();
4029 int32_t metaState = incomingKey.getMetaState();
4030 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004031 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004032 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08004033 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004034 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4035 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4036 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4039 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004040 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004041
4042 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4043 android::base::Timer t;
4044 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4045 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4046 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4047 std::to_string(t.duration().count()).c_str());
4048 }
4049 }
4050
4051 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004052 std::unique_ptr<KeyEntry> injectedEntry =
4053 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
4054 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
4055 incomingKey.getDisplayId(), policyFlags, action,
4056 flags, keyCode, incomingKey.getScanCode(), metaState,
4057 incomingKey.getRepeatCount(),
4058 incomingKey.getDownTime());
4059 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 }
4062
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 case AINPUT_EVENT_TYPE_MOTION: {
4064 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
4065 int32_t action = motionEvent->getAction();
4066 size_t pointerCount = motionEvent->getPointerCount();
4067 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
4068 int32_t actionButton = motionEvent->getActionButton();
4069 int32_t displayId = motionEvent->getDisplayId();
4070 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004071 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004072 }
4073
4074 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4075 nsecs_t eventTime = motionEvent->getEventTime();
4076 android::base::Timer t;
4077 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4078 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4079 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4080 std::to_string(t.duration().count()).c_str());
4081 }
4082 }
4083
4084 mLock.lock();
4085 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
4086 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004087 std::unique_ptr<MotionEntry> injectedEntry =
4088 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4089 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4090 motionEvent->getDisplayId(), policyFlags, action,
4091 actionButton, motionEvent->getFlags(),
4092 motionEvent->getMetaState(),
4093 motionEvent->getButtonState(),
4094 motionEvent->getClassification(),
4095 motionEvent->getEdgeFlags(),
4096 motionEvent->getXPrecision(),
4097 motionEvent->getYPrecision(),
4098 motionEvent->getRawXCursorPosition(),
4099 motionEvent->getRawYCursorPosition(),
4100 motionEvent->getDownTime(),
4101 uint32_t(pointerCount), pointerProperties,
4102 samplePointerCoords, motionEvent->getXOffset(),
4103 motionEvent->getYOffset());
4104 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004105 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
4106 sampleEventTimes += 1;
4107 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108 std::unique_ptr<MotionEntry> nextInjectedEntry =
4109 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4110 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4111 motionEvent->getDisplayId(), policyFlags,
4112 action, actionButton, motionEvent->getFlags(),
4113 motionEvent->getMetaState(),
4114 motionEvent->getButtonState(),
4115 motionEvent->getClassification(),
4116 motionEvent->getEdgeFlags(),
4117 motionEvent->getXPrecision(),
4118 motionEvent->getYPrecision(),
4119 motionEvent->getRawXCursorPosition(),
4120 motionEvent->getRawYCursorPosition(),
4121 motionEvent->getDownTime(),
4122 uint32_t(pointerCount), pointerProperties,
4123 samplePointerCoords,
4124 motionEvent->getXOffset(),
4125 motionEvent->getYOffset());
4126 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 }
4128 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004132 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004133 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 }
4135
4136 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004137 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 injectionState->injectionIsAsync = true;
4139 }
4140
4141 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004142 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143
4144 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004145 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004147 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 }
4149
4150 mLock.unlock();
4151
4152 if (needWake) {
4153 mLooper->wake();
4154 }
4155
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004156 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004158 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004160 if (syncMode == InputEventInjectionSync::NONE) {
4161 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 } else {
4163 for (;;) {
4164 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004165 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 break;
4167 }
4168
4169 nsecs_t remainingTimeout = endTime - now();
4170 if (remainingTimeout <= 0) {
4171#if DEBUG_INJECTION
4172 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004175 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 break;
4177 }
4178
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004179 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004182 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4183 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 while (injectionState->pendingForegroundDispatches != 0) {
4185#if DEBUG_INJECTION
4186 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188#endif
4189 nsecs_t remainingTimeout = endTime - now();
4190 if (remainingTimeout <= 0) {
4191#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4193 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004195 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 break;
4197 }
4198
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004199 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 }
4201 }
4202 }
4203
4204 injectionState->release();
4205 } // release lock
4206
4207#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004208 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210#endif
4211
4212 return injectionResult;
4213}
4214
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004215std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004216 std::array<uint8_t, 32> calculatedHmac;
4217 std::unique_ptr<VerifiedInputEvent> result;
4218 switch (event.getType()) {
4219 case AINPUT_EVENT_TYPE_KEY: {
4220 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4221 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4222 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004223 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004224 break;
4225 }
4226 case AINPUT_EVENT_TYPE_MOTION: {
4227 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4228 VerifiedMotionEvent verifiedMotionEvent =
4229 verifiedMotionEventFromMotionEvent(motionEvent);
4230 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004231 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004232 break;
4233 }
4234 default: {
4235 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4236 return nullptr;
4237 }
4238 }
4239 if (calculatedHmac == INVALID_HMAC) {
4240 return nullptr;
4241 }
4242 if (calculatedHmac != event.getHmac()) {
4243 return nullptr;
4244 }
4245 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004246}
4247
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 return injectorUid == 0 ||
4250 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251}
4252
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004253void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004254 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004255 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 if (injectionState) {
4257#if DEBUG_INJECTION
4258 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 "injectorPid=%d, injectorUid=%d",
4260 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261#endif
4262
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 // Log the outcome since the injector did not wait for the injection result.
4265 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 ALOGV("Asynchronous input event injection succeeded.");
4268 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004269 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004270 ALOGW("Asynchronous input event injection failed.");
4271 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004272 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 ALOGW("Asynchronous input event injection permission denied.");
4274 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004275 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004276 ALOGW("Asynchronous input event injection timed out.");
4277 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004278 case InputEventInjectionResult::PENDING:
4279 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4280 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 }
4282 }
4283
4284 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004285 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 }
4287}
4288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004289void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4290 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 if (injectionState) {
4292 injectionState->pendingForegroundDispatches += 1;
4293 }
4294}
4295
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004296void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4297 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 if (injectionState) {
4299 injectionState->pendingForegroundDispatches -= 1;
4300
4301 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004302 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 }
4304 }
4305}
4306
Vishnu Nairad321cd2020-08-20 16:40:21 -07004307const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004308 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004309 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4310 auto it = mWindowHandlesByDisplay.find(displayId);
4311 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004312}
4313
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004315 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004316 if (windowHandleToken == nullptr) {
4317 return nullptr;
4318 }
4319
Arthur Hungb92218b2018-08-14 12:00:21 +08004320 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004321 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004322 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004323 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004324 return windowHandle;
4325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 }
4327 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004328 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329}
4330
Vishnu Nairad321cd2020-08-20 16:40:21 -07004331sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4332 int displayId) const {
4333 if (windowHandleToken == nullptr) {
4334 return nullptr;
4335 }
4336
4337 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4338 if (windowHandle->getToken() == windowHandleToken) {
4339 return windowHandle;
4340 }
4341 }
4342 return nullptr;
4343}
4344
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004345sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4346 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004347 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004348 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004349 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004350 if (handle->getId() == windowHandle->getId() &&
4351 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004352 if (windowHandle->getInfo()->displayId != it.first) {
4353 ALOGE("Found window %s in display %" PRId32
4354 ", but it should belong to display %" PRId32,
4355 windowHandle->getName().c_str(), it.first,
4356 windowHandle->getInfo()->displayId);
4357 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004358 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
4361 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004362 return nullptr;
4363}
4364
4365sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4366 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4367 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368}
4369
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004370bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4371 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4372 const bool noInputChannel =
4373 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4374 if (connection != nullptr && noInputChannel) {
4375 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4376 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4377 return false;
4378 }
4379
4380 if (connection == nullptr) {
4381 if (!noInputChannel) {
4382 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4383 }
4384 return false;
4385 }
4386 if (!connection->responsive) {
4387 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4388 return false;
4389 }
4390 return true;
4391}
4392
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004393std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4394 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004395 auto connectionIt = mConnectionsByToken.find(token);
4396 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004397 return nullptr;
4398 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004399 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004400}
4401
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004402void InputDispatcher::updateWindowHandlesForDisplayLocked(
4403 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4404 if (inputWindowHandles.empty()) {
4405 // Remove all handles on a display if there are no windows left.
4406 mWindowHandlesByDisplay.erase(displayId);
4407 return;
4408 }
4409
4410 // Since we compare the pointer of input window handles across window updates, we need
4411 // to make sure the handle object for the same window stays unchanged across updates.
4412 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004413 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004414 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004415 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004416 }
4417
4418 std::vector<sp<InputWindowHandle>> newHandles;
4419 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4420 if (!handle->updateInfo()) {
4421 // handle no longer valid
4422 continue;
4423 }
4424
4425 const InputWindowInfo* info = handle->getInfo();
4426 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4427 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4428 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004429 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4430 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4431 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004432 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004433 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004434 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004435 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004436 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004437 }
4438
4439 if (info->displayId != displayId) {
4440 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4441 handle->getName().c_str(), displayId, info->displayId);
4442 continue;
4443 }
4444
Robert Carredd13602020-04-13 17:24:34 -07004445 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4446 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004447 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004448 oldHandle->updateFrom(handle);
4449 newHandles.push_back(oldHandle);
4450 } else {
4451 newHandles.push_back(handle);
4452 }
4453 }
4454
4455 // Insert or replace
4456 mWindowHandlesByDisplay[displayId] = newHandles;
4457}
4458
Arthur Hung72d8dc32020-03-28 00:48:39 +00004459void InputDispatcher::setInputWindows(
4460 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4461 { // acquire lock
4462 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004463 for (const auto& [displayId, handles] : handlesPerDisplay) {
4464 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004465 }
4466 }
4467 // Wake up poll loop since it may need to make new input dispatching choices.
4468 mLooper->wake();
4469}
4470
Arthur Hungb92218b2018-08-14 12:00:21 +08004471/**
4472 * Called from InputManagerService, update window handle list by displayId that can receive input.
4473 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4474 * If set an empty list, remove all handles from the specific display.
4475 * For focused handle, check if need to change and send a cancel event to previous one.
4476 * For removed handle, check if need to send a cancel event if already in touch.
4477 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004478void InputDispatcher::setInputWindowsLocked(
4479 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004480 if (DEBUG_FOCUS) {
4481 std::string windowList;
4482 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4483 windowList += iwh->getName() + " ";
4484 }
4485 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004488 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4489 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4490 const bool noInputWindow =
4491 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4492 if (noInputWindow && window->getToken() != nullptr) {
4493 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4494 window->getName().c_str());
4495 window->releaseChannel();
4496 }
4497 }
4498
Arthur Hung72d8dc32020-03-28 00:48:39 +00004499 // Copy old handles for release if they are no longer present.
4500 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004502 // Save the old windows' orientation by ID before it gets updated.
4503 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4504 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4505 oldWindowOrientations.emplace(handle->getId(),
4506 handle->getInfo()->transform.getOrientation());
4507 }
4508
Arthur Hung72d8dc32020-03-28 00:48:39 +00004509 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004510
Vishnu Nair958da932020-08-21 17:12:37 -07004511 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4512 if (mLastHoverWindowHandle &&
4513 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4514 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004515 mLastHoverWindowHandle = nullptr;
4516 }
4517
Vishnu Nairc519ff72021-01-21 08:23:08 -08004518 std::optional<FocusResolver::FocusChanges> changes =
4519 mFocusResolver.setInputWindows(displayId, windowHandles);
4520 if (changes) {
4521 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004524 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4525 mTouchStatesByDisplay.find(displayId);
4526 if (stateIt != mTouchStatesByDisplay.end()) {
4527 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004528 for (size_t i = 0; i < state.windows.size();) {
4529 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004530 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004531 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004532 ALOGD("Touched window was removed: %s in display %" PRId32,
4533 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004534 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004535 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004536 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4537 if (touchedInputChannel != nullptr) {
4538 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4539 "touched window was removed");
4540 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004542 state.windows.erase(state.windows.begin() + i);
4543 } else {
4544 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 }
4546 }
arthurhungb89ccb02020-12-30 16:19:01 +08004547
arthurhung6d4bed92021-03-17 11:59:33 +08004548 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004549 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004550 if (mDragState &&
4551 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004552 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004553 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004554 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004555 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004556
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004557 if (isPerWindowInputRotationEnabled()) {
4558 // Determine if the orientation of any of the input windows have changed, and cancel all
4559 // pointer events if necessary.
4560 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4561 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4562 if (newWindowHandle != nullptr &&
4563 newWindowHandle->getInfo()->transform.getOrientation() !=
4564 oldWindowOrientations[oldWindowHandle->getId()]) {
4565 std::shared_ptr<InputChannel> inputChannel =
4566 getInputChannelLocked(newWindowHandle->getToken());
4567 if (inputChannel != nullptr) {
4568 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4569 "touched window's orientation changed");
4570 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4571 }
4572 }
4573 }
4574 }
4575
Arthur Hung72d8dc32020-03-28 00:48:39 +00004576 // Release information for windows that are no longer present.
4577 // This ensures that unused input channels are released promptly.
4578 // Otherwise, they might stick around until the window handle is destroyed
4579 // which might not happen until the next GC.
4580 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004581 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004582 if (DEBUG_FOCUS) {
4583 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004584 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004585 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004586 // To avoid making too many calls into the compat framework, only
4587 // check for window flags when windows are going away.
4588 // TODO(b/157929241) : delete this. This is only needed temporarily
4589 // in order to gather some data about the flag usage
4590 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4591 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4592 oldWindowHandle->getName().c_str());
4593 if (mCompatService != nullptr) {
4594 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4595 oldWindowHandle->getInfo()->ownerUid);
4596 }
4597 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004598 }
chaviw291d88a2019-02-14 10:33:58 -08004599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600}
4601
4602void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004603 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004604 if (DEBUG_FOCUS) {
4605 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4606 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4607 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004608 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004609 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610
Chris Yea209fde2020-07-22 13:54:51 -07004611 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004612 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004613
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004614 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4615 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616 }
4617
Chris Yea209fde2020-07-22 13:54:51 -07004618 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004619 if (inputApplicationHandle != nullptr) {
4620 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4621 } else {
4622 mFocusedApplicationHandlesByDisplay.erase(displayId);
4623 }
4624
4625 // No matter what the old focused application was, stop waiting on it because it is
4626 // no longer focused.
4627 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 } // release lock
4629
4630 // Wake up poll loop since it may need to make new input dispatching choices.
4631 mLooper->wake();
4632}
4633
Tiger Huang721e26f2018-07-24 22:26:19 +08004634/**
4635 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4636 * the display not specified.
4637 *
4638 * We track any unreleased events for each window. If a window loses the ability to receive the
4639 * released event, we will send a cancel event to it. So when the focused display is changed, we
4640 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4641 * display. The display-specified events won't be affected.
4642 */
4643void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004644 if (DEBUG_FOCUS) {
4645 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4646 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004647 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004648 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004649
4650 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004651 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004652 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004653 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004654 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004655 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004656 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004657 CancelationOptions
4658 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4659 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004660 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004661 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4662 }
4663 }
4664 mFocusedDisplayId = displayId;
4665
Chris Ye3c2d6f52020-08-09 10:39:48 -07004666 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004667 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004668 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004669
Vishnu Nairad321cd2020-08-20 16:40:21 -07004670 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004671 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004672 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004673 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004674 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004675 }
4676 }
4677 }
4678
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004679 if (DEBUG_FOCUS) {
4680 logDispatchStateLocked();
4681 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004682 } // release lock
4683
4684 // Wake up poll loop since it may need to make new input dispatching choices.
4685 mLooper->wake();
4686}
4687
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004689 if (DEBUG_FOCUS) {
4690 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692
4693 bool changed;
4694 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004695 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
4697 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4698 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004699 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 }
4701
4702 if (mDispatchEnabled && !enabled) {
4703 resetAndDropEverythingLocked("dispatcher is being disabled");
4704 }
4705
4706 mDispatchEnabled = enabled;
4707 mDispatchFrozen = frozen;
4708 changed = true;
4709 } else {
4710 changed = false;
4711 }
4712
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004713 if (DEBUG_FOCUS) {
4714 logDispatchStateLocked();
4715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 } // release lock
4717
4718 if (changed) {
4719 // Wake up poll loop since it may need to make new input dispatching choices.
4720 mLooper->wake();
4721 }
4722}
4723
4724void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004725 if (DEBUG_FOCUS) {
4726 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728
4729 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004730 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731
4732 if (mInputFilterEnabled == enabled) {
4733 return;
4734 }
4735
4736 mInputFilterEnabled = enabled;
4737 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4738 } // release lock
4739
4740 // Wake up poll loop since there might be work to do to drop everything.
4741 mLooper->wake();
4742}
4743
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004744void InputDispatcher::setInTouchMode(bool inTouchMode) {
4745 std::scoped_lock lock(mLock);
4746 mInTouchMode = inTouchMode;
4747}
4748
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004749void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4750 if (opacity < 0 || opacity > 1) {
4751 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4752 return;
4753 }
4754
4755 std::scoped_lock lock(mLock);
4756 mMaximumObscuringOpacityForTouch = opacity;
4757}
4758
4759void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4760 std::scoped_lock lock(mLock);
4761 mBlockUntrustedTouchesMode = mode;
4762}
4763
arthurhungb89ccb02020-12-30 16:19:01 +08004764bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4765 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004766 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004767 if (DEBUG_FOCUS) {
4768 ALOGD("Trivial transfer to same window.");
4769 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004770 return true;
4771 }
4772
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004774 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775
chaviwfbe5d9c2018-12-26 12:23:37 -08004776 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4777 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004778 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004779 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 return false;
4781 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004782 if (DEBUG_FOCUS) {
4783 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4784 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004787 if (DEBUG_FOCUS) {
4788 ALOGD("Cannot transfer focus because windows are on different displays.");
4789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 return false;
4791 }
4792
4793 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004794 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4795 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004796 for (size_t i = 0; i < state.windows.size(); i++) {
4797 const TouchedWindow& touchedWindow = state.windows[i];
4798 if (touchedWindow.windowHandle == fromWindowHandle) {
4799 int32_t oldTargetFlags = touchedWindow.targetFlags;
4800 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004802 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004804 int32_t newTargetFlags = oldTargetFlags &
4805 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4806 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004807 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808
arthurhungb89ccb02020-12-30 16:19:01 +08004809 // Store the dragging window.
4810 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004811 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004812 }
4813
Jeff Brownf086ddb2014-02-11 14:28:48 -08004814 found = true;
4815 goto Found;
4816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 }
4818 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004819 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004821 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004822 if (DEBUG_FOCUS) {
4823 ALOGD("Focus transfer failed because from window did not have focus.");
4824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 return false;
4826 }
4827
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004828 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4829 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004830 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004831 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 CancelationOptions
4833 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4834 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004836 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 }
4838
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004839 if (DEBUG_FOCUS) {
4840 logDispatchStateLocked();
4841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 } // release lock
4843
4844 // Wake up poll loop since it may need to make new input dispatching choices.
4845 mLooper->wake();
4846 return true;
4847}
4848
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004849// Binder call
4850bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4851 sp<IBinder> fromToken;
4852 { // acquire lock
4853 std::scoped_lock _l(mLock);
4854
4855 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4856 if (toWindowHandle == nullptr) {
4857 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4858 return false;
4859 }
4860
4861 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4862
4863 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4864 if (touchStateIt == mTouchStatesByDisplay.end()) {
4865 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4866 displayId);
4867 return false;
4868 }
4869
4870 TouchState& state = touchStateIt->second;
4871 if (state.windows.size() != 1) {
4872 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4873 state.windows.size());
4874 return false;
4875 }
4876 const TouchedWindow& touchedWindow = state.windows[0];
4877 fromToken = touchedWindow.windowHandle->getToken();
4878 } // release lock
4879
4880 return transferTouchFocus(fromToken, destChannelToken);
4881}
4882
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004884 if (DEBUG_FOCUS) {
4885 ALOGD("Resetting and dropping all events (%s).", reason);
4886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887
4888 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4889 synthesizeCancelationEventsForAllConnectionsLocked(options);
4890
4891 resetKeyRepeatLocked();
4892 releasePendingEventLocked();
4893 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004897 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004899 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900}
4901
4902void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004903 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 dumpDispatchStateLocked(dump);
4905
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004906 std::istringstream stream(dump);
4907 std::string line;
4908
4909 while (std::getline(stream, line, '\n')) {
4910 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 }
4912}
4913
Prabir Pradhan99987712020-11-10 18:43:05 -08004914std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4915 std::string dump;
4916
4917 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4918 toString(mFocusedWindowRequestedPointerCapture));
4919
4920 std::string windowName = "None";
4921 if (mWindowTokenWithPointerCapture) {
4922 const sp<InputWindowHandle> captureWindowHandle =
4923 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4924 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4925 : "token has capture without window";
4926 }
4927 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4928
4929 return dump;
4930}
4931
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004932void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004933 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4934 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4935 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004936 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937
Tiger Huang721e26f2018-07-24 22:26:19 +08004938 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4939 dump += StringPrintf(INDENT "FocusedApplications:\n");
4940 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4941 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004942 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004943 const std::chrono::duration timeout =
4944 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004946 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004947 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004950 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004952
Vishnu Nairc519ff72021-01-21 08:23:08 -08004953 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004954 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004956 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004957 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004958 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4959 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004960 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004961 state.displayId, toString(state.down), toString(state.split),
4962 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004963 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004964 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004965 for (size_t i = 0; i < state.windows.size(); i++) {
4966 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004967 dump += StringPrintf(INDENT4
4968 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4969 i, touchedWindow.windowHandle->getName().c_str(),
4970 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004971 }
4972 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004973 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004974 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004975 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004976 dump += INDENT3 "Portal windows:\n";
4977 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004978 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004979 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4980 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004981 }
4982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983 }
4984 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004985 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986 }
4987
arthurhung6d4bed92021-03-17 11:59:33 +08004988 if (mDragState) {
4989 dump += StringPrintf(INDENT "DragState:\n");
4990 mDragState->dump(dump, INDENT2);
4991 }
4992
Arthur Hungb92218b2018-08-14 12:00:21 +08004993 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004994 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004995 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004996 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004997 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004998 dump += INDENT2 "Windows:\n";
4999 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005000 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08005001 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005003 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005004 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005005 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005006 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005008 "applicationInfo.name=%s, "
5009 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005010 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005011 i, windowInfo->name.c_str(), windowInfo->id,
5012 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005013 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005014 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005015 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005016 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005017 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005018 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005019 windowInfo->frameLeft, windowInfo->frameTop,
5020 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005021 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005022 windowInfo->applicationInfo.name.c_str(),
5023 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005024 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005025 dump += StringPrintf(", inputFeatures=%s",
5026 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005027 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005028 "ms, trustedOverlay=%s, hasToken=%s, "
5029 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005030 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005031 millis(windowInfo->dispatchingTimeout),
5032 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005033 toString(windowInfo->token != nullptr),
5034 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005035 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005036 }
5037 } else {
5038 dump += INDENT2 "Windows: <none>\n";
5039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 }
5041 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005042 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 }
5044
Michael Wright3dd60e22019-03-27 22:06:44 +00005045 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005046 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005047 const std::vector<Monitor>& monitors = it.second;
5048 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5049 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005050 }
5051 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005052 const std::vector<Monitor>& monitors = it.second;
5053 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5054 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005057 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 }
5059
5060 nsecs_t currentTime = now();
5061
5062 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005063 if (!mRecentQueue.empty()) {
5064 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005065 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005066 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005067 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005068 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 }
5070 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005071 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072 }
5073
5074 // Dump event currently being dispatched.
5075 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005076 dump += INDENT "PendingEvent:\n";
5077 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005078 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005079 dump += StringPrintf(", age=%" PRId64 "ms\n",
5080 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005082 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083 }
5084
5085 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005086 if (!mInboundQueue.empty()) {
5087 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005088 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005089 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005090 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005091 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 }
5093 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005094 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 }
5096
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005097 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005098 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005099 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5100 const KeyReplacement& replacement = pair.first;
5101 int32_t newKeyCode = pair.second;
5102 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005103 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005104 }
5105 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005107 }
5108
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005109 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005110 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005111 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005112 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005114 connection->inputChannel->getFd().get(),
5115 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005116 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005117 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005119 if (!connection->outboundQueue.empty()) {
5120 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5121 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005122 dump += dumpQueue(connection->outboundQueue, currentTime);
5123
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005125 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 }
5127
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005128 if (!connection->waitQueue.empty()) {
5129 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5130 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005131 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005133 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 }
5135 }
5136 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005137 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 }
5139
5140 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005141 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5142 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005144 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005147 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005148 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5149 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5150 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005151 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005152 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153}
5154
Michael Wright3dd60e22019-03-27 22:06:44 +00005155void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5156 const size_t numMonitors = monitors.size();
5157 for (size_t i = 0; i < numMonitors; i++) {
5158 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005159 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005160 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5161 dump += "\n";
5162 }
5163}
5164
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005165class LooperEventCallback : public LooperCallback {
5166public:
5167 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5168 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5169
5170private:
5171 std::function<int(int events)> mCallback;
5172};
5173
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005174Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005175#if DEBUG_CHANNEL_CREATION
5176 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177#endif
5178
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005179 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005180 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005181 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005182
5183 if (result) {
5184 return base::Error(result) << "Failed to open input channel pair with name " << name;
5185 }
5186
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005188 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005189 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005190 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005191 sp<Connection> connection =
5192 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005194 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5195 ALOGE("Created a new connection, but the token %p is already known", token.get());
5196 }
5197 mConnectionsByToken.emplace(token, connection);
5198
5199 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5200 this, std::placeholders::_1, token);
5201
5202 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 } // release lock
5204
5205 // Wake the looper because some connections have changed.
5206 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005207 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208}
5209
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005210Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5211 bool isGestureMonitor,
5212 const std::string& name,
5213 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005214 std::shared_ptr<InputChannel> serverChannel;
5215 std::unique_ptr<InputChannel> clientChannel;
5216 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5217 if (result) {
5218 return base::Error(result) << "Failed to open input channel pair with name " << name;
5219 }
5220
Michael Wright3dd60e22019-03-27 22:06:44 +00005221 { // acquire lock
5222 std::scoped_lock _l(mLock);
5223
5224 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005225 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5226 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005227 }
5228
Garfield Tan15601662020-09-22 15:32:38 -07005229 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005230 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005231 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005232
5233 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5234 ALOGE("Created a new connection, but the token %p is already known", token.get());
5235 }
5236 mConnectionsByToken.emplace(token, connection);
5237 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5238 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005240 auto& monitorsByDisplay =
5241 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005242 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005243
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005244 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005245 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5246 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005247 }
Garfield Tan15601662020-09-22 15:32:38 -07005248
Michael Wright3dd60e22019-03-27 22:06:44 +00005249 // Wake the looper because some connections have changed.
5250 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005251 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005252}
5253
Garfield Tan15601662020-09-22 15:32:38 -07005254status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005256 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257
Garfield Tan15601662020-09-22 15:32:38 -07005258 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 if (status) {
5260 return status;
5261 }
5262 } // release lock
5263
5264 // Wake the poll loop because removing the connection may have changed the current
5265 // synchronization state.
5266 mLooper->wake();
5267 return OK;
5268}
5269
Garfield Tan15601662020-09-22 15:32:38 -07005270status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5271 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005272 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005273 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005274 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275 return BAD_VALUE;
5276 }
5277
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005278 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005279
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005281 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 }
5283
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005284 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285
5286 nsecs_t currentTime = now();
5287 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5288
5289 connection->status = Connection::STATUS_ZOMBIE;
5290 return OK;
5291}
5292
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005293void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5294 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5295 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005296}
5297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005298void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005299 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005300 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005301 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005302 std::vector<Monitor>& monitors = it->second;
5303 const size_t numMonitors = monitors.size();
5304 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005305 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005306 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5307 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005308 monitors.erase(monitors.begin() + i);
5309 break;
5310 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005311 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005312 if (monitors.empty()) {
5313 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005314 } else {
5315 ++it;
5316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 }
5318}
5319
Michael Wright3dd60e22019-03-27 22:06:44 +00005320status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5321 { // acquire lock
5322 std::scoped_lock _l(mLock);
5323 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5324
5325 if (!foundDisplayId) {
5326 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5327 return BAD_VALUE;
5328 }
5329 int32_t displayId = foundDisplayId.value();
5330
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005331 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5332 mTouchStatesByDisplay.find(displayId);
5333 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005334 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5335 return BAD_VALUE;
5336 }
5337
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005338 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005339 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 std::optional<int32_t> foundDeviceId;
5341 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005342 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005343 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005344 foundDeviceId = state.deviceId;
5345 }
5346 }
5347 if (!foundDeviceId || !state.down) {
5348 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005349 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005350 return BAD_VALUE;
5351 }
5352 int32_t deviceId = foundDeviceId.value();
5353
5354 // Send cancel events to all the input channels we're stealing from.
5355 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005356 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005357 options.deviceId = deviceId;
5358 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005359 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005360 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005361 std::shared_ptr<InputChannel> channel =
5362 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005363 if (channel != nullptr) {
5364 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005365 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005366 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005367 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005368 canceledWindows += "]";
5369 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5370 canceledWindows.c_str());
5371
Michael Wright3dd60e22019-03-27 22:06:44 +00005372 // Then clear the current touch state so we stop dispatching to them as well.
5373 state.filterNonMonitors();
5374 }
5375 return OK;
5376}
5377
Prabir Pradhan99987712020-11-10 18:43:05 -08005378void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5379 { // acquire lock
5380 std::scoped_lock _l(mLock);
5381 if (DEBUG_FOCUS) {
5382 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5383 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5384 windowHandle != nullptr ? windowHandle->getName().c_str()
5385 : "token without window");
5386 }
5387
Vishnu Nairc519ff72021-01-21 08:23:08 -08005388 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005389 if (focusedToken != windowToken) {
5390 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5391 enabled ? "enable" : "disable");
5392 return;
5393 }
5394
5395 if (enabled == mFocusedWindowRequestedPointerCapture) {
5396 ALOGW("Ignoring request to %s Pointer Capture: "
5397 "window has %s requested pointer capture.",
5398 enabled ? "enable" : "disable", enabled ? "already" : "not");
5399 return;
5400 }
5401
5402 mFocusedWindowRequestedPointerCapture = enabled;
5403 setPointerCaptureLocked(enabled);
5404 } // release lock
5405
5406 // Wake the thread to process command entries.
5407 mLooper->wake();
5408}
5409
Michael Wright3dd60e22019-03-27 22:06:44 +00005410std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5411 const sp<IBinder>& token) {
5412 for (const auto& it : mGestureMonitorsByDisplay) {
5413 const std::vector<Monitor>& monitors = it.second;
5414 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005415 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005416 return it.first;
5417 }
5418 }
5419 }
5420 return std::nullopt;
5421}
5422
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005423std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5424 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5425 if (gesturePid.has_value()) {
5426 return gesturePid;
5427 }
5428 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5429}
5430
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005431sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005432 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005433 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005434 }
5435
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005436 for (const auto& [token, connection] : mConnectionsByToken) {
5437 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005438 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 }
5440 }
Robert Carr4e670e52018-08-15 13:26:12 -07005441
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005442 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443}
5444
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005445std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5446 sp<Connection> connection = getConnectionLocked(connectionToken);
5447 if (connection == nullptr) {
5448 return "<nullptr>";
5449 }
5450 return connection->getInputChannelName();
5451}
5452
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005453void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005454 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005455 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005456}
5457
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005458void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5459 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005460 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005461 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5462 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 commandEntry->connection = connection;
5464 commandEntry->eventTime = currentTime;
5465 commandEntry->seq = seq;
5466 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005467 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005468 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469}
5470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005471void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5472 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005474 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005476 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5477 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005479 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480}
5481
Vishnu Nairad321cd2020-08-20 16:40:21 -07005482void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5483 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005484 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5485 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005486 commandEntry->oldToken = oldToken;
5487 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005488 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005489}
5490
arthurhungf452d0b2021-01-06 00:19:52 +08005491void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5492 std::unique_ptr<CommandEntry> commandEntry =
5493 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5494 commandEntry->newToken = token;
5495 commandEntry->x = x;
5496 commandEntry->y = y;
5497 postCommandLocked(std::move(commandEntry));
5498}
5499
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005500void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5501 if (connection == nullptr) {
5502 LOG_ALWAYS_FATAL("Caller must check for nullness");
5503 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005504 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5505 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005506 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005507 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005508 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005509 return;
5510 }
5511 /**
5512 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5513 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5514 * has changed. This could cause newer entries to time out before the already dispatched
5515 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5516 * processes the events linearly. So providing information about the oldest entry seems to be
5517 * most useful.
5518 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005519 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005520 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5521 std::string reason =
5522 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005523 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005524 ns2ms(currentWait),
5525 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005526 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005527 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005528
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005529 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5530
5531 // Stop waking up for events on this connection, it is already unresponsive
5532 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005533}
5534
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005535void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5536 std::string reason =
5537 StringPrintf("%s does not have a focused window", application->getName().c_str());
5538 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005539
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005540 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5541 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5542 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005543 postCommandLocked(std::move(commandEntry));
5544}
5545
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005546void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5547 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5548 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5549 commandEntry->obscuringPackage = obscuringPackage;
5550 postCommandLocked(std::move(commandEntry));
5551}
5552
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005553void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5554 const std::string& reason) {
5555 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5556 updateLastAnrStateLocked(windowLabel, reason);
5557}
5558
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005559void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5560 const std::string& reason) {
5561 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562 updateLastAnrStateLocked(windowLabel, reason);
5563}
5564
5565void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5566 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005568 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 struct tm tm;
5570 localtime_r(&t, &tm);
5571 char timestr[64];
5572 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005573 mLastAnrState.clear();
5574 mLastAnrState += INDENT "ANR:\n";
5575 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005576 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5577 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005578 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579}
5580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005581void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 mLock.unlock();
5583
5584 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5585
5586 mLock.lock();
5587}
5588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005589void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 sp<Connection> connection = commandEntry->connection;
5591
5592 if (connection->status != Connection::STATUS_ZOMBIE) {
5593 mLock.unlock();
5594
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005595 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596
5597 mLock.lock();
5598 }
5599}
5600
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005601void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005602 sp<IBinder> oldToken = commandEntry->oldToken;
5603 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005604 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005605 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005606 mLock.lock();
5607}
5608
arthurhungf452d0b2021-01-06 00:19:52 +08005609void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5610 sp<IBinder> newToken = commandEntry->newToken;
5611 mLock.unlock();
5612 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5613 mLock.lock();
5614}
5615
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005616void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005618
5619 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5620
5621 mLock.lock();
5622}
5623
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005624void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005625 mLock.unlock();
5626
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005627 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628
5629 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005630}
5631
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005632void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005633 mLock.unlock();
5634
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005635 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5636
5637 mLock.lock();
5638}
5639
5640void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5641 mLock.unlock();
5642
5643 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5644
5645 mLock.lock();
5646}
5647
5648void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5649 mLock.unlock();
5650
5651 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005652
5653 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005654}
5655
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005656void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5657 mLock.unlock();
5658
5659 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5660
5661 mLock.lock();
5662}
5663
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5665 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005666 KeyEntry& entry = *(commandEntry->keyEntry);
5667 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668
5669 mLock.unlock();
5670
Michael Wright2b3c3302018-03-02 17:19:13 +00005671 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005672 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005673 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005674 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5675 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005676 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678
5679 mLock.lock();
5680
5681 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005682 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005684 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005686 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5687 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689}
5690
chaviwfd6d3512019-03-25 13:23:49 -07005691void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5692 mLock.unlock();
5693 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5694 mLock.lock();
5695}
5696
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005697/**
5698 * Connection is responsive if it has no events in the waitQueue that are older than the
5699 * current time.
5700 */
5701static bool isConnectionResponsive(const Connection& connection) {
5702 const nsecs_t currentTime = now();
5703 for (const DispatchEntry* entry : connection.waitQueue) {
5704 if (entry->timeoutTime < currentTime) {
5705 return false;
5706 }
5707 }
5708 return true;
5709}
5710
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005711void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005713 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005715 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716
5717 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005718 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005719 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005720 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005722 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005723 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005724 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005725 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5726 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005727 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005728 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5729 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5730 connection->inputChannel->getConnectionToken(),
5731 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5732 finishTime);
5733 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005734
5735 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005736 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005737 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005738 restartEvent =
5739 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005740 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005741 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005742 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5743 handled);
5744 } else {
5745 restartEvent = false;
5746 }
5747
5748 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005749 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005750 // contents of the wait queue to have been drained, so we need to double-check
5751 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005752 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5753 if (dispatchEntryIt != connection->waitQueue.end()) {
5754 dispatchEntry = *dispatchEntryIt;
5755 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005756 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5757 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005758 if (!connection->responsive) {
5759 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005760 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005761 // The connection was unresponsive, and now it's responsive.
5762 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005763 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005764 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005765 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005766 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005767 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005768 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005769 } else {
5770 releaseDispatchEntry(dispatchEntry);
5771 }
5772 }
5773
5774 // Start the next dispatch cycle for this connection.
5775 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776}
5777
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005778void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5779 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5780 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5781 monitorUnresponsiveCommand->pid = pid;
5782 monitorUnresponsiveCommand->reason = std::move(reason);
5783 postCommandLocked(std::move(monitorUnresponsiveCommand));
5784}
5785
5786void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5787 std::string reason) {
5788 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5789 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5790 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5791 windowUnresponsiveCommand->reason = std::move(reason);
5792 postCommandLocked(std::move(windowUnresponsiveCommand));
5793}
5794
5795void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5796 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5797 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5798 monitorResponsiveCommand->pid = pid;
5799 postCommandLocked(std::move(monitorResponsiveCommand));
5800}
5801
5802void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5803 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5804 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5805 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5806 postCommandLocked(std::move(windowResponsiveCommand));
5807}
5808
5809/**
5810 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5811 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5812 * command entry to the command queue.
5813 */
5814void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5815 std::string reason) {
5816 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5817 if (connection.monitor) {
5818 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5819 reason.c_str());
5820 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5821 if (!pid.has_value()) {
5822 ALOGE("Could not find unresponsive monitor for connection %s",
5823 connection.inputChannel->getName().c_str());
5824 return;
5825 }
5826 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5827 return;
5828 }
5829 // If not a monitor, must be a window
5830 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5831 reason.c_str());
5832 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5833}
5834
5835/**
5836 * Tell the policy that a connection has become responsive so that it can stop ANR.
5837 */
5838void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5839 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5840 if (connection.monitor) {
5841 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5842 if (!pid.has_value()) {
5843 ALOGE("Could not find responsive monitor for connection %s",
5844 connection.inputChannel->getName().c_str());
5845 return;
5846 }
5847 sendMonitorResponsiveCommandLocked(pid.value());
5848 return;
5849 }
5850 // If not a monitor, must be a window
5851 sendWindowResponsiveCommandLocked(connectionToken);
5852}
5853
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005855 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005856 KeyEntry& keyEntry, bool handled) {
5857 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005858 if (!handled) {
5859 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005860 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005861 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005862 return false;
5863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005865 // Get the fallback key state.
5866 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005867 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005868 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005869 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005870 connection->inputState.removeFallbackKey(originalKeyCode);
5871 }
5872
5873 if (handled || !dispatchEntry->hasForegroundTarget()) {
5874 // If the application handles the original key for which we previously
5875 // generated a fallback or if the window is not a foreground window,
5876 // then cancel the associated fallback key, if any.
5877 if (fallbackKeyCode != -1) {
5878 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005881 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005882 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005884 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005885 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886
5887 mLock.unlock();
5888
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005889 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005890 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891
5892 mLock.lock();
5893
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005894 // Cancel the fallback key.
5895 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897 "application handled the original non-fallback key "
5898 "or is no longer a foreground target, "
5899 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900 options.keyCode = fallbackKeyCode;
5901 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005903 connection->inputState.removeFallbackKey(originalKeyCode);
5904 }
5905 } else {
5906 // If the application did not handle a non-fallback key, first check
5907 // that we are in a good state to perform unhandled key event processing
5908 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005909 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005910 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005913 "since this is not an initial down. "
5914 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005915 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005917 return false;
5918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005920 // Dispatch the unhandled key to the policy.
5921#if DEBUG_OUTBOUND_EVENT_DETAILS
5922 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005923 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005924 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005925#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005926 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005927
5928 mLock.unlock();
5929
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005930 bool fallback =
5931 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005933
5934 mLock.lock();
5935
5936 if (connection->status != Connection::STATUS_NORMAL) {
5937 connection->inputState.removeFallbackKey(originalKeyCode);
5938 return false;
5939 }
5940
5941 // Latch the fallback keycode for this key on an initial down.
5942 // The fallback keycode cannot change at any other point in the lifecycle.
5943 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005945 fallbackKeyCode = event.getKeyCode();
5946 } else {
5947 fallbackKeyCode = AKEYCODE_UNKNOWN;
5948 }
5949 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5950 }
5951
5952 ALOG_ASSERT(fallbackKeyCode != -1);
5953
5954 // Cancel the fallback key if the policy decides not to send it anymore.
5955 // We will continue to dispatch the key to the policy but we will no
5956 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005957 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5958 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959#if DEBUG_OUTBOUND_EVENT_DETAILS
5960 if (fallback) {
5961 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005962 "as a fallback for %d, but on the DOWN it had requested "
5963 "to send %d instead. Fallback canceled.",
5964 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005965 } else {
5966 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005967 "but on the DOWN it had requested to send %d. "
5968 "Fallback canceled.",
5969 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005970 }
5971#endif
5972
5973 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5974 "canceling fallback, policy no longer desires it");
5975 options.keyCode = fallbackKeyCode;
5976 synthesizeCancelationEventsForConnectionLocked(connection, options);
5977
5978 fallback = false;
5979 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005980 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005981 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005982 }
5983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984
5985#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005986 {
5987 std::string msg;
5988 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5989 connection->inputState.getFallbackKeys();
5990 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005991 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005994 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005995 }
5996#endif
5997
5998 if (fallback) {
5999 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006000 keyEntry.eventTime = event.getEventTime();
6001 keyEntry.deviceId = event.getDeviceId();
6002 keyEntry.source = event.getSource();
6003 keyEntry.displayId = event.getDisplayId();
6004 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6005 keyEntry.keyCode = fallbackKeyCode;
6006 keyEntry.scanCode = event.getScanCode();
6007 keyEntry.metaState = event.getMetaState();
6008 keyEntry.repeatCount = event.getRepeatCount();
6009 keyEntry.downTime = event.getDownTime();
6010 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006011
6012#if DEBUG_OUTBOUND_EVENT_DETAILS
6013 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006014 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006015 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006016#endif
6017 return true; // restart the event
6018 } else {
6019#if DEBUG_OUTBOUND_EVENT_DETAILS
6020 ALOGD("Unhandled key event: No fallback key.");
6021#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006022
6023 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006024 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006025 }
6026 }
6027 return false;
6028}
6029
6030bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006031 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006032 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033 return false;
6034}
6035
6036void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6037 mLock.unlock();
6038
Sean Stoutb4e0a592021-02-23 07:34:53 -08006039 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6040 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041
6042 mLock.lock();
6043}
6044
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045void InputDispatcher::traceInboundQueueLengthLocked() {
6046 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006047 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 }
6049}
6050
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006051void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 if (ATRACE_ENABLED()) {
6053 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006054 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6055 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056 }
6057}
6058
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006059void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 if (ATRACE_ENABLED()) {
6061 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006062 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6063 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064 }
6065}
6066
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006067void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006068 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006070 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 dumpDispatchStateLocked(dump);
6072
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006073 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006074 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006075 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 }
6077}
6078
6079void InputDispatcher::monitor() {
6080 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006081 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006083 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084}
6085
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006086/**
6087 * Wake up the dispatcher and wait until it processes all events and commands.
6088 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6089 * this method can be safely called from any thread, as long as you've ensured that
6090 * the work you are interested in completing has already been queued.
6091 */
6092bool InputDispatcher::waitForIdle() {
6093 /**
6094 * Timeout should represent the longest possible time that a device might spend processing
6095 * events and commands.
6096 */
6097 constexpr std::chrono::duration TIMEOUT = 100ms;
6098 std::unique_lock lock(mLock);
6099 mLooper->wake();
6100 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6101 return result == std::cv_status::no_timeout;
6102}
6103
Vishnu Naire798b472020-07-23 13:52:21 -07006104/**
6105 * Sets focus to the window identified by the token. This must be called
6106 * after updating any input window handles.
6107 *
6108 * Params:
6109 * request.token - input channel token used to identify the window that should gain focus.
6110 * request.focusedToken - the token that the caller expects currently to be focused. If the
6111 * specified token does not match the currently focused window, this request will be dropped.
6112 * If the specified focused token matches the currently focused window, the call will succeed.
6113 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6114 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6115 * when requesting the focus change. This determines which request gets
6116 * precedence if there is a focus change request from another source such as pointer down.
6117 */
Vishnu Nair958da932020-08-21 17:12:37 -07006118void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6119 { // acquire lock
6120 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006121 std::optional<FocusResolver::FocusChanges> changes =
6122 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6123 if (changes) {
6124 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006125 }
6126 } // release lock
6127 // Wake up poll loop since it may need to make new input dispatching choices.
6128 mLooper->wake();
6129}
6130
Vishnu Nairc519ff72021-01-21 08:23:08 -08006131void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6132 if (changes.oldFocus) {
6133 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006134 if (focusedInputChannel) {
6135 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6136 "focus left window");
6137 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006138 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006139 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006140 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006141 if (changes.newFocus) {
6142 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006143 }
6144
Prabir Pradhan99987712020-11-10 18:43:05 -08006145 // If a window has pointer capture, then it must have focus. We need to ensure that this
6146 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6147 // If the window loses focus before it loses pointer capture, then the window can be in a state
6148 // where it has pointer capture but not focus, violating the contract. Therefore we must
6149 // dispatch the pointer capture event before the focus event. Since focus events are added to
6150 // the front of the queue (above), we add the pointer capture event to the front of the queue
6151 // after the focus events are added. This ensures the pointer capture event ends up at the
6152 // front.
6153 disablePointerCaptureForcedLocked();
6154
Vishnu Nairc519ff72021-01-21 08:23:08 -08006155 if (mFocusedDisplayId == changes.displayId) {
6156 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006157 }
6158}
Vishnu Nair958da932020-08-21 17:12:37 -07006159
Prabir Pradhan99987712020-11-10 18:43:05 -08006160void InputDispatcher::disablePointerCaptureForcedLocked() {
6161 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6162 return;
6163 }
6164
6165 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6166
6167 if (mFocusedWindowRequestedPointerCapture) {
6168 mFocusedWindowRequestedPointerCapture = false;
6169 setPointerCaptureLocked(false);
6170 }
6171
6172 if (!mWindowTokenWithPointerCapture) {
6173 // No need to send capture changes because no window has capture.
6174 return;
6175 }
6176
6177 if (mPendingEvent != nullptr) {
6178 // Move the pending event to the front of the queue. This will give the chance
6179 // for the pending event to be dropped if it is a captured event.
6180 mInboundQueue.push_front(mPendingEvent);
6181 mPendingEvent = nullptr;
6182 }
6183
6184 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6185 false /* hasCapture */);
6186 mInboundQueue.push_front(std::move(entry));
6187}
6188
Prabir Pradhan99987712020-11-10 18:43:05 -08006189void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6190 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6191 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6192 commandEntry->enabled = enabled;
6193 postCommandLocked(std::move(commandEntry));
6194}
6195
6196void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6197 android::inputdispatcher::CommandEntry* commandEntry) {
6198 mLock.unlock();
6199
6200 mPolicy->setPointerCapture(commandEntry->enabled);
6201
6202 mLock.lock();
6203}
6204
Garfield Tane84e6f92019-08-29 17:28:41 -07006205} // namespace android::inputdispatcher