blob: 8ea71fe69dc0729b6772606fee1d82d64a378274 [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 <statslog.h>
63#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wright44753b12020-07-08 13:48:11 +010066#include <cerrno>
67#include <cinttypes>
68#include <climits>
69#include <cstddef>
70#include <ctime>
71#include <queue>
72#include <sstream>
73
74#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070075#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010076
Michael Wrightd02c5b62014-02-10 15:10:22 -080077#define INDENT " "
78#define INDENT2 " "
79#define INDENT3 " "
80#define INDENT4 " "
81
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000083using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080084using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080085using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080087using android::os::InputEventInjectionResult;
88using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100089using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080090
Garfield Tane84e6f92019-08-29 17:28:41 -070091namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// Default input dispatching timeout if there is no focused application or paused window
94// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080095const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
96 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
97 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
99// Amount of time to allow for all pending events to be processed when an app switch
100// key is on the way. This is used to preempt input dispatch and drop input events
101// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Amount of time to allow for an event to be dispatched (measured since its eventTime)
105// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// 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 +0000109constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
110
111// Log a warning when an interception call takes longer than this to process.
112constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700114// Additional key latency in case a connection is still processing some motion events.
115// This will help with the case when a user touched a button that opens a new window,
116// and gives us the chance to dispatch the key to this new window.
117constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
118
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000120constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
121
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000122// Event log tags. See EventLogTags.logtags for reference
123constexpr int LOGTAG_INPUT_INTERACTION = 62000;
124constexpr int LOGTAG_INPUT_FOCUS = 62001;
125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126static inline nsecs_t now() {
127 return systemTime(SYSTEM_TIME_MONOTONIC);
128}
129
130static inline const char* toString(bool value) {
131 return value ? "true" : "false";
132}
133
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000134static inline const std::string toString(sp<IBinder> binder) {
135 if (binder == nullptr) {
136 return "<null>";
137 }
138 return StringPrintf("%p", binder.get());
139}
140
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
143 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144}
145
146static bool isValidKeyAction(int32_t action) {
147 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700148 case AKEY_EVENT_ACTION_DOWN:
149 case AKEY_EVENT_ACTION_UP:
150 return true;
151 default:
152 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153 }
154}
155
156static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800158 ALOGE("Key event has invalid action code 0x%x", action);
159 return false;
160 }
161 return true;
162}
163
Michael Wright7b159c92015-05-14 14:48:03 +0100164static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_DOWN:
167 case AMOTION_EVENT_ACTION_UP:
168 case AMOTION_EVENT_ACTION_CANCEL:
169 case AMOTION_EVENT_ACTION_MOVE:
170 case AMOTION_EVENT_ACTION_OUTSIDE:
171 case AMOTION_EVENT_ACTION_HOVER_ENTER:
172 case AMOTION_EVENT_ACTION_HOVER_MOVE:
173 case AMOTION_EVENT_ACTION_HOVER_EXIT:
174 case AMOTION_EVENT_ACTION_SCROLL:
175 return true;
176 case AMOTION_EVENT_ACTION_POINTER_DOWN:
177 case AMOTION_EVENT_ACTION_POINTER_UP: {
178 int32_t index = getMotionEventActionPointerIndex(action);
179 return index >= 0 && index < pointerCount;
180 }
181 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
182 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
183 return actionButton != 0;
184 default:
185 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 }
187}
188
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500189static int64_t millis(std::chrono::nanoseconds t) {
190 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
191}
192
Michael Wright7b159c92015-05-14 14:48:03 +0100193static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 const PointerProperties* pointerProperties) {
195 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 ALOGE("Motion event has invalid action code 0x%x", action);
197 return false;
198 }
199 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000200 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700201 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 return false;
203 }
204 BitSet32 pointerIdBits;
205 for (size_t i = 0; i < pointerCount; i++) {
206 int32_t id = pointerProperties[i].id;
207 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700208 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
209 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 return false;
211 }
212 if (pointerIdBits.hasBit(id)) {
213 ALOGE("Motion event has duplicate pointer id %d", id);
214 return false;
215 }
216 pointerIdBits.markBit(id);
217 }
218 return true;
219}
220
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000221static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000223 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
225
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000226 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 bool first = true;
228 Region::const_iterator cur = region.begin();
229 Region::const_iterator const tail = region.end();
230 while (cur != tail) {
231 if (first) {
232 first = false;
233 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800236 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 cur++;
238 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000239 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240}
241
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500242static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
243 constexpr size_t maxEntries = 50; // max events to print
244 constexpr size_t skipBegin = maxEntries / 2;
245 const size_t skipEnd = queue.size() - maxEntries / 2;
246 // skip from maxEntries / 2 ... size() - maxEntries/2
247 // only print from 0 .. skipBegin and then from skipEnd .. size()
248
249 std::string dump;
250 for (size_t i = 0; i < queue.size(); i++) {
251 const DispatchEntry& entry = *queue[i];
252 if (i >= skipBegin && i < skipEnd) {
253 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
254 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
255 continue;
256 }
257 dump.append(INDENT4);
258 dump += entry.eventEntry->getDescription();
259 dump += StringPrintf(", seq=%" PRIu32
260 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
261 entry.seq, entry.targetFlags, entry.resolvedAction,
262 ns2ms(currentTime - entry.eventEntry->eventTime));
263 if (entry.deliveryTime != 0) {
264 // This entry was delivered, so add information on how long we've been waiting
265 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
266 }
267 dump.append("\n");
268 }
269 return dump;
270}
271
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700272/**
273 * Find the entry in std::unordered_map by key, and return it.
274 * If the entry is not found, return a default constructed entry.
275 *
276 * Useful when the entries are vectors, since an empty vector will be returned
277 * if the entry is not found.
278 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
279 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700280template <typename K, typename V>
281static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700282 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700283 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800284}
285
chaviwaf87b3e2019-10-01 16:59:28 -0700286static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
287 if (first == second) {
288 return true;
289 }
290
291 if (first == nullptr || second == nullptr) {
292 return false;
293 }
294
295 return first->getToken() == second->getToken();
296}
297
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000298static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
299 if (first == nullptr || second == nullptr) {
300 return false;
301 }
302 return first->applicationInfo.token != nullptr &&
303 first->applicationInfo.token == second->applicationInfo.token;
304}
305
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800306static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
307 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
308}
309
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700311 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000312 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900313 if (eventEntry->type == EventEntry::Type::MOTION) {
314 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800315 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900316 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800317 // Use identity transform for events that are not pointer events because their axes
318 // values do not represent on-screen coordinates, so they should not have any window
319 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900320 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700321 1.0f /*globalScaleFactor*/,
322 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900323 }
324 }
325
chaviw1ff3d1e2020-07-01 15:53:47 -0700326 if (inputTarget.useDefaultPointerTransform()) {
327 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700328 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700329 inputTarget.globalScaleFactor,
330 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331 }
332
333 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
334 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
335
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700336 std::vector<PointerCoords> pointerCoords;
337 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338
339 // Use the first pointer information to normalize all other pointers. This could be any pointer
340 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700341 // uses the transform for the normalized pointer.
342 const ui::Transform& firstPointerTransform =
343 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
344 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 // Iterate through all pointers in the event to normalize against the first.
347 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
348 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
349 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700350 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000351
352 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 // First, apply the current pointer's transform to update the coordinates into
354 // window space.
355 pointerCoords[pointerIndex].transform(currTransform);
356 // Next, apply the inverse transform of the normalized coordinates so the
357 // current coordinates are transformed into the normalized coordinate space.
358 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359 }
360
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700361 std::unique_ptr<MotionEntry> combinedMotionEntry =
362 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
363 motionEntry.deviceId, motionEntry.source,
364 motionEntry.displayId, motionEntry.policyFlags,
365 motionEntry.action, motionEntry.actionButton,
366 motionEntry.flags, motionEntry.metaState,
367 motionEntry.buttonState, motionEntry.classification,
368 motionEntry.edgeFlags, motionEntry.xPrecision,
369 motionEntry.yPrecision, motionEntry.xCursorPosition,
370 motionEntry.yCursorPosition, motionEntry.downTime,
371 motionEntry.pointerCount, motionEntry.pointerProperties,
372 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000373
374 if (motionEntry.injectionState) {
375 combinedMotionEntry->injectionState = motionEntry.injectionState;
376 combinedMotionEntry->injectionState->refCount += 1;
377 }
378
379 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700380 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700381 firstPointerTransform, inputTarget.globalScaleFactor,
382 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000383 return dispatchEntry;
384}
385
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700386static void addGestureMonitors(const std::vector<Monitor>& monitors,
387 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
388 float yOffset = 0) {
389 if (monitors.empty()) {
390 return;
391 }
392 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
393 for (const Monitor& monitor : monitors) {
394 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
395 }
396}
397
Garfield Tan15601662020-09-22 15:32:38 -0700398static status_t openInputChannelPair(const std::string& name,
399 std::shared_ptr<InputChannel>& serverChannel,
400 std::unique_ptr<InputChannel>& clientChannel) {
401 std::unique_ptr<InputChannel> uniqueServerChannel;
402 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
403
404 serverChannel = std::move(uniqueServerChannel);
405 return result;
406}
407
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500408template <typename T>
409static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
410 if (lhs == nullptr && rhs == nullptr) {
411 return true;
412 }
413 if (lhs == nullptr || rhs == nullptr) {
414 return false;
415 }
416 return *lhs == *rhs;
417}
418
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000419static sp<IPlatformCompatNative> getCompatService() {
420 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
421 if (service == nullptr) {
422 ALOGE("Failed to link to compat service");
423 return nullptr;
424 }
425 return interface_cast<IPlatformCompatNative>(service);
426}
427
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000428static KeyEvent createKeyEvent(const KeyEntry& entry) {
429 KeyEvent event;
430 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
431 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
432 entry.repeatCount, entry.downTime, entry.eventTime);
433 return event;
434}
435
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000436static std::optional<int32_t> findMonitorPidByToken(
437 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
438 const sp<IBinder>& token) {
439 for (const auto& it : monitorsByDisplay) {
440 const std::vector<Monitor>& monitors = it.second;
441 for (const Monitor& monitor : monitors) {
442 if (monitor.inputChannel->getConnectionToken() == token) {
443 return monitor.pid;
444 }
445 }
446 }
447 return std::nullopt;
448}
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450// --- InputDispatcher ---
451
Garfield Tan00f511d2019-06-12 16:55:40 -0700452InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
453 : mPolicy(policy),
454 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700455 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800456 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700457 mAppSwitchSawKeyDown(false),
458 mAppSwitchDueTime(LONG_LONG_MAX),
459 mNextUnblockedEvent(nullptr),
460 mDispatchEnabled(false),
461 mDispatchFrozen(false),
462 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800463 // mInTouchMode will be initialized by the WindowManager to the default device config.
464 // To avoid leaking stack in case that call never comes, and for tests,
465 // initialize it here anyways.
466 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100467 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000468 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800469 mFocusedWindowRequestedPointerCapture(false),
470 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000471 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800473 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474
Yi Kong9b14ac62018-07-17 13:48:38 -0700475 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476
477 policy->getDispatcherConfiguration(&mConfig);
478}
479
480InputDispatcher::~InputDispatcher() {
481 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800482 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483
484 resetKeyRepeatLocked();
485 releasePendingEventLocked();
486 drainInboundQueueLocked();
487 }
488
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000489 while (!mConnectionsByToken.empty()) {
490 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700491 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 }
493}
494
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700495status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700496 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700497 return ALREADY_EXISTS;
498 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700499 mThread = std::make_unique<InputThread>(
500 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
501 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700502}
503
504status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700505 if (mThread && mThread->isCallingThread()) {
506 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700507 return INVALID_OPERATION;
508 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700509 mThread.reset();
510 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700511}
512
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513void InputDispatcher::dispatchOnce() {
514 nsecs_t nextWakeupTime = LONG_LONG_MAX;
515 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800516 std::scoped_lock _l(mLock);
517 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518
519 // Run a dispatch loop if there are no pending commands.
520 // The dispatch loop might enqueue commands to run afterwards.
521 if (!haveCommandsLocked()) {
522 dispatchOnceInnerLocked(&nextWakeupTime);
523 }
524
525 // Run all pending commands if there are any.
526 // If any commands were run then force the next poll to wake up immediately.
527 if (runCommandsLockedInterruptible()) {
528 nextWakeupTime = LONG_LONG_MIN;
529 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800530
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700531 // If we are still waiting for ack on some events,
532 // we might have to wake up earlier to check if an app is anr'ing.
533 const nsecs_t nextAnrCheck = processAnrsLocked();
534 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
535
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800536 // We are about to enter an infinitely long sleep, because we have no commands or
537 // pending or queued events
538 if (nextWakeupTime == LONG_LONG_MAX) {
539 mDispatcherEnteredIdle.notify_all();
540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541 } // release lock
542
543 // Wait for callback or timeout or wake. (make sure we round up, not down)
544 nsecs_t currentTime = now();
545 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
546 mLooper->pollOnce(timeoutMillis);
547}
548
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700549/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500550 * Raise ANR if there is no focused window.
551 * Before the ANR is raised, do a final state check:
552 * 1. The currently focused application must be the same one we are waiting for.
553 * 2. Ensure we still don't have a focused window.
554 */
555void InputDispatcher::processNoFocusedWindowAnrLocked() {
556 // Check if the application that we are waiting for is still focused.
557 std::shared_ptr<InputApplicationHandle> focusedApplication =
558 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
559 if (focusedApplication == nullptr ||
560 focusedApplication->getApplicationToken() !=
561 mAwaitedFocusedApplication->getApplicationToken()) {
562 // Unexpected because we should have reset the ANR timer when focused application changed
563 ALOGE("Waited for a focused window, but focused application has already changed to %s",
564 focusedApplication->getName().c_str());
565 return; // The focused application has changed.
566 }
567
568 const sp<InputWindowHandle>& focusedWindowHandle =
569 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
570 if (focusedWindowHandle != nullptr) {
571 return; // We now have a focused window. No need for ANR.
572 }
573 onAnrLocked(mAwaitedFocusedApplication);
574}
575
576/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700577 * Check if any of the connections' wait queues have events that are too old.
578 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
579 * Return the time at which we should wake up next.
580 */
581nsecs_t InputDispatcher::processAnrsLocked() {
582 const nsecs_t currentTime = now();
583 nsecs_t nextAnrCheck = LONG_LONG_MAX;
584 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
585 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
586 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500587 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700588 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500589 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700590 return LONG_LONG_MIN;
591 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500592 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700593 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
594 }
595 }
596
597 // Check if any connection ANRs are due
598 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
599 if (currentTime < nextAnrCheck) { // most likely scenario
600 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
601 }
602
603 // If we reached here, we have an unresponsive connection.
604 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
605 if (connection == nullptr) {
606 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
607 return nextAnrCheck;
608 }
609 connection->responsive = false;
610 // Stop waking up for this unresponsive connection
611 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000612 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700613 return LONG_LONG_MIN;
614}
615
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500616std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700617 sp<InputWindowHandle> window = getWindowHandleLocked(token);
618 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500619 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700620 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500621 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700622}
623
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
625 nsecs_t currentTime = now();
626
Jeff Browndc5992e2014-04-11 01:27:26 -0700627 // Reset the key repeat timer whenever normal dispatch is suspended while the
628 // device is in a non-interactive state. This is to ensure that we abort a key
629 // repeat if the device is just coming out of sleep.
630 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 resetKeyRepeatLocked();
632 }
633
634 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
635 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100636 if (DEBUG_FOCUS) {
637 ALOGD("Dispatch frozen. Waiting some more.");
638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 return;
640 }
641
642 // Optimize latency of app switches.
643 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
644 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
645 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
646 if (mAppSwitchDueTime < *nextWakeupTime) {
647 *nextWakeupTime = mAppSwitchDueTime;
648 }
649
650 // Ready to start a new event.
651 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700653 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 if (isAppSwitchDue) {
655 // The inbound queue is empty so the app switch key we were waiting
656 // for will never arrive. Stop waiting for it.
657 resetPendingAppSwitchLocked(false);
658 isAppSwitchDue = false;
659 }
660
661 // Synthesize a key repeat if appropriate.
662 if (mKeyRepeatState.lastKeyEntry) {
663 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
664 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
665 } else {
666 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
667 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
668 }
669 }
670 }
671
672 // Nothing to do if there is no pending event.
673 if (!mPendingEvent) {
674 return;
675 }
676 } else {
677 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700678 mPendingEvent = mInboundQueue.front();
679 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 traceInboundQueueLengthLocked();
681 }
682
683 // Poke user activity for this event.
684 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700685 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 }
688
689 // Now we have an event to dispatch.
690 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700691 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700693 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700695 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700697 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699
700 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700701 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 }
703
704 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700705 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700706 const ConfigurationChangedEntry& typedEntry =
707 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700708 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700709 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 break;
711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700713 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700714 const DeviceResetEntry& typedEntry =
715 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700717 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700718 break;
719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100721 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700722 std::shared_ptr<FocusEntry> typedEntry =
723 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100724 dispatchFocusLocked(currentTime, typedEntry);
725 done = true;
726 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
727 break;
728 }
729
Prabir Pradhan99987712020-11-10 18:43:05 -0800730 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
731 const auto typedEntry =
732 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
733 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
734 done = true;
735 break;
736 }
737
arthurhungb89ccb02020-12-30 16:19:01 +0800738 case EventEntry::Type::DRAG: {
739 std::shared_ptr<DragEntry> typedEntry =
740 std::static_pointer_cast<DragEntry>(mPendingEvent);
741 dispatchDragLocked(currentTime, typedEntry);
742 done = true;
743 break;
744 }
745
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700746 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700747 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700748 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700749 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700750 resetPendingAppSwitchLocked(true);
751 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700752 } else if (dropReason == DropReason::NOT_DROPPED) {
753 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700754 }
755 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700756 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700757 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700759 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
760 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700762 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700763 break;
764 }
765
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700766 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700767 std::shared_ptr<MotionEntry> motionEntry =
768 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700769 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
770 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700772 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700775 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
776 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700778 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
Chris Yef59a2f42020-10-16 12:55:26 -0700781
782 case EventEntry::Type::SENSOR: {
783 std::shared_ptr<SensorEntry> sensorEntry =
784 std::static_pointer_cast<SensorEntry>(mPendingEvent);
785 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
786 dropReason = DropReason::APP_SWITCH;
787 }
788 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
789 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
790 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
791 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
792 dropReason = DropReason::STALE;
793 }
794 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
795 done = true;
796 break;
797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
799
800 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700801 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700802 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
Michael Wright3a981722015-06-10 15:26:13 +0100804 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805
806 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
809}
810
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700811/**
812 * Return true if the events preceding this incoming motion event should be dropped
813 * Return false otherwise (the default behaviour)
814 */
815bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700816 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700817 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700818
819 // Optimize case where the current application is unresponsive and the user
820 // decides to touch a window in a different application.
821 // If the application takes too long to catch up then we drop all events preceding
822 // the touch into the other window.
823 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700824 int32_t displayId = motionEntry.displayId;
825 int32_t x = static_cast<int32_t>(
826 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
827 int32_t y = static_cast<int32_t>(
828 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
829 sp<InputWindowHandle> touchedWindowHandle =
830 findTouchedWindowAtLocked(displayId, x, y, nullptr);
831 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700832 touchedWindowHandle->getApplicationToken() !=
833 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700834 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700835 ALOGI("Pruning input queue because user touched a different application while waiting "
836 "for %s",
837 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700838 return true;
839 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840
841 // Alternatively, maybe there's a gesture monitor that could handle this event
842 std::vector<TouchedMonitor> gestureMonitors =
843 findTouchedGestureMonitorsLocked(displayId, {});
844 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
845 sp<Connection> connection =
846 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000847 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700848 // This monitor could take more input. Drop all events preceding this
849 // event, so that gesture monitor could get a chance to receive the stream
850 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
851 "responsive gesture monitor that may handle the event",
852 mAwaitedFocusedApplication->getName().c_str());
853 return true;
854 }
855 }
856 }
857
858 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
859 // yet been processed by some connections, the dispatcher will wait for these motion
860 // events to be processed before dispatching the key event. This is because these motion events
861 // may cause a new window to be launched, which the user might expect to receive focus.
862 // To prevent waiting forever for such events, just send the key to the currently focused window
863 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
864 ALOGD("Received a new pointer down event, stop waiting for events to process and "
865 "just send the pending key event to the focused window.");
866 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700867 }
868 return false;
869}
870
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700872 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 mInboundQueue.push_back(std::move(newEntry));
874 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 traceInboundQueueLengthLocked();
876
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700877 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700878 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 // Optimize app switch latency.
880 // If the application takes too long to catch up then we drop all events preceding
881 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700882 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700884 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700886 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700891 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700892 mAppSwitchSawKeyDown = false;
893 needWake = true;
894 }
895 }
896 }
897 break;
898 }
899
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700900 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700901 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
902 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700903 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100907 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700908 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
909 break;
910 }
911 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800912 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700913 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800914 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
915 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700916 // nothing to do
917 break;
918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 }
920
921 return needWake;
922}
923
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700924void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700925 // Do not store sensor event in recent queue to avoid flooding the queue.
926 if (entry->type != EventEntry::Type::SENSOR) {
927 mRecentQueue.push_back(entry);
928 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700929 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700930 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
932}
933
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700935 int32_t y, TouchState* touchState,
936 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800937 bool addPortalWindows,
938 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700939 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
940 LOG_ALWAYS_FATAL(
941 "Must provide a valid touch state if adding portal windows or outside targets");
942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700944 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800945 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +0800946 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +0800947 continue;
948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 const InputWindowInfo* windowInfo = windowHandle->getInfo();
950 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100951 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952
953 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100954 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
955 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
956 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800958 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 if (portalToDisplayId != ADISPLAY_ID_NONE &&
960 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800961 if (addPortalWindows) {
962 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700963 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800964 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700965 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 // Found window.
969 return windowHandle;
970 }
971 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800972
Michael Wright44753b12020-07-08 13:48:11 +0100973 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700974 touchState->addOrUpdateWindow(windowHandle,
975 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
976 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700981 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982}
983
Garfield Tane84e6f92019-08-29 17:28:41 -0700984std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700985 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000986 std::vector<TouchedMonitor> touchedMonitors;
987
988 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
989 addGestureMonitors(monitors, touchedMonitors);
990 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
991 const InputWindowInfo* windowInfo = portalWindow->getInfo();
992 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
994 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000995 }
996 return touchedMonitors;
997}
998
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 const char* reason;
1001 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001002 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 reason = "inbound event was dropped because the policy consumed it";
1007 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001008 case DropReason::DISABLED:
1009 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 ALOGI("Dropped event because input dispatch is disabled.");
1011 }
1012 reason = "inbound event was dropped because input dispatch is disabled";
1013 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001014 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 ALOGI("Dropped event because of pending overdue app switch.");
1016 reason = "inbound event was dropped because of pending overdue app switch";
1017 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001018 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 ALOGI("Dropped event because the current application is not responding and the user "
1020 "has started interacting with a different application.");
1021 reason = "inbound event was dropped because the current application is not responding "
1022 "and the user has started interacting with a different application";
1023 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001024 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 ALOGI("Dropped event because it is stale.");
1026 reason = "inbound event was dropped because it is stale";
1027 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001028 case DropReason::NO_POINTER_CAPTURE:
1029 ALOGI("Dropped event because there is no window with Pointer Capture.");
1030 reason = "inbound event was dropped because there is no window with Pointer Capture";
1031 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001032 case DropReason::NOT_DROPPED: {
1033 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001034 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
1037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001039 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1041 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001044 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001045 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1046 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1048 synthesizeCancelationEventsForAllConnectionsLocked(options);
1049 } else {
1050 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1051 synthesizeCancelationEventsForAllConnectionsLocked(options);
1052 }
1053 break;
1054 }
Chris Yef59a2f42020-10-16 12:55:26 -07001055 case EventEntry::Type::SENSOR: {
1056 break;
1057 }
arthurhungb89ccb02020-12-30 16:19:01 +08001058 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1059 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001060 break;
1061 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001062 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001063 case EventEntry::Type::CONFIGURATION_CHANGED:
1064 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001065 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 break;
1067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069}
1070
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001071static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1073 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074}
1075
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001076bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1077 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1078 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1079 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080}
1081
1082bool InputDispatcher::isAppSwitchPendingLocked() {
1083 return mAppSwitchDueTime != LONG_LONG_MAX;
1084}
1085
1086void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1087 mAppSwitchDueTime = LONG_LONG_MAX;
1088
1089#if DEBUG_APP_SWITCH
1090 if (handled) {
1091 ALOGD("App switch has arrived.");
1092 } else {
1093 ALOGD("App switch was abandoned.");
1094 }
1095#endif
1096}
1097
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001099 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100}
1101
1102bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001103 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 return false;
1105 }
1106
1107 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001108 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001109 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001111 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112
1113 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001114 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 return true;
1116}
1117
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001118void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1119 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120}
1121
1122void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001123 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001124 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001125 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 releaseInboundEventLocked(entry);
1127 }
1128 traceInboundQueueLengthLocked();
1129}
1130
1131void InputDispatcher::releasePendingEventLocked() {
1132 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001134 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 }
1136}
1137
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001138void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001140 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141#if DEBUG_DISPATCH_CYCLE
1142 ALOGD("Injected inbound event was dropped.");
1143#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001144 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 }
1146 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001147 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150}
1151
1152void InputDispatcher::resetKeyRepeatLocked() {
1153 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001154 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156}
1157
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001158std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1159 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160
Michael Wright2e732952014-09-24 13:26:59 -07001161 uint32_t policyFlags = entry->policyFlags &
1162 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001164 std::shared_ptr<KeyEntry> newEntry =
1165 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1166 entry->source, entry->displayId, policyFlags, entry->action,
1167 entry->flags, entry->keyCode, entry->scanCode,
1168 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001170 newEntry->syntheticRepeat = true;
1171 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001173 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174}
1175
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001177 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001179 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180#endif
1181
1182 // Reset key repeating in case a keyboard device was added or removed or something.
1183 resetKeyRepeatLocked();
1184
1185 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001186 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1187 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001189 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 return true;
1191}
1192
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1194 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1197 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198#endif
1199
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001200 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 synthesizeCancelationEventsForAllConnectionsLocked(options);
1203 return true;
1204}
1205
Vishnu Nairad321cd2020-08-20 16:40:21 -07001206void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001207 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001208 if (mPendingEvent != nullptr) {
1209 // Move the pending event to the front of the queue. This will give the chance
1210 // for the pending event to get dispatched to the newly focused window
1211 mInboundQueue.push_front(mPendingEvent);
1212 mPendingEvent = nullptr;
1213 }
1214
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 std::unique_ptr<FocusEntry> focusEntry =
1216 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1217 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001218
1219 // This event should go to the front of the queue, but behind all other focus events
1220 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001221 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001222 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223 [](const std::shared_ptr<EventEntry>& event) {
1224 return event->type == EventEntry::Type::FOCUS;
1225 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001226
1227 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001229}
1230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001232 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001233 if (channel == nullptr) {
1234 return; // Window has gone away
1235 }
1236 InputTarget target;
1237 target.inputChannel = channel;
1238 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1239 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001240 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1241 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001242 std::string reason = std::string("reason=").append(entry->reason);
1243 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001244 dispatchEventLocked(currentTime, entry, {target});
1245}
1246
Prabir Pradhan99987712020-11-10 18:43:05 -08001247void InputDispatcher::dispatchPointerCaptureChangedLocked(
1248 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1249 DropReason& dropReason) {
1250 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001251 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1252 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1253 }
1254 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001255 // Pointer capture was already forcefully disabled because of focus change.
1256 dropReason = DropReason::NOT_DROPPED;
1257 return;
1258 }
1259
1260 // Set drop reason for early returns
1261 dropReason = DropReason::NO_POINTER_CAPTURE;
1262
1263 sp<IBinder> token;
1264 if (entry->pointerCaptureEnabled) {
1265 // Enable Pointer Capture
1266 if (!mFocusedWindowRequestedPointerCapture) {
1267 // This can happen if a window requests capture and immediately releases capture.
1268 ALOGW("No window requested Pointer Capture.");
1269 return;
1270 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001271 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001272 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1273 mWindowTokenWithPointerCapture = token;
1274 } else {
1275 // Disable Pointer Capture
1276 token = mWindowTokenWithPointerCapture;
1277 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001278 if (mFocusedWindowRequestedPointerCapture) {
1279 mFocusedWindowRequestedPointerCapture = false;
1280 setPointerCaptureLocked(false);
1281 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001282 }
1283
1284 auto channel = getInputChannelLocked(token);
1285 if (channel == nullptr) {
1286 // Window has gone away, clean up Pointer Capture state.
1287 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001288 if (mFocusedWindowRequestedPointerCapture) {
1289 mFocusedWindowRequestedPointerCapture = false;
1290 setPointerCaptureLocked(false);
1291 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001292 return;
1293 }
1294 InputTarget target;
1295 target.inputChannel = channel;
1296 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1297 entry->dispatchInProgress = true;
1298 dispatchEventLocked(currentTime, entry, {target});
1299
1300 dropReason = DropReason::NOT_DROPPED;
1301}
1302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001306 if (!entry->dispatchInProgress) {
1307 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1308 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1309 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1310 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001311 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 // We have seen two identical key downs in a row which indicates that the device
1313 // driver is automatically generating key repeats itself. We take note of the
1314 // repeat here, but we disable our own next key repeat timer since it is clear that
1315 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001316 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1317 // Make sure we don't get key down from a different device. If a different
1318 // device Id has same key pressed down, the new device Id will replace the
1319 // current one to hold the key repeat with repeat count reset.
1320 // In the future when got a KEY_UP on the device id, drop it and do not
1321 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1323 resetKeyRepeatLocked();
1324 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1325 } else {
1326 // Not a repeat. Save key down state in case we do see a repeat later.
1327 resetKeyRepeatLocked();
1328 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1329 }
1330 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001331 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1332 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001333 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001334#if DEBUG_INBOUND_EVENT_DETAILS
1335 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1336#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001337 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 resetKeyRepeatLocked();
1339 }
1340
1341 if (entry->repeatCount == 1) {
1342 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1343 } else {
1344 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1345 }
1346
1347 entry->dispatchInProgress = true;
1348
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001349 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 }
1351
1352 // Handle case where the policy asked us to try again later last time.
1353 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1354 if (currentTime < entry->interceptKeyWakeupTime) {
1355 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1356 *nextWakeupTime = entry->interceptKeyWakeupTime;
1357 }
1358 return false; // wait until next wakeup
1359 }
1360 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1361 entry->interceptKeyWakeupTime = 0;
1362 }
1363
1364 // Give the policy a chance to intercept the key.
1365 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1366 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001367 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001368 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001369 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001370 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001371 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001373 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 return false; // wait for the command to run
1375 } else {
1376 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1377 }
1378 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001379 if (*dropReason == DropReason::NOT_DROPPED) {
1380 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 }
1382 }
1383
1384 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001385 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001386 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001387 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1388 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001389 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 return true;
1391 }
1392
1393 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001394 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001395 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001396 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001397 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 return false;
1399 }
1400
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001401 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001402 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 return true;
1404 }
1405
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001406 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408
1409 // Dispatch the key.
1410 dispatchEventLocked(currentTime, entry, inputTargets);
1411 return true;
1412}
1413
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001414void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001416 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001417 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1418 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001419 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1420 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1421 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422#endif
1423}
1424
Chris Yef59a2f42020-10-16 12:55:26 -07001425void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1426 mLock.unlock();
1427
1428 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1429 if (entry->accuracyChanged) {
1430 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1431 }
1432 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1433 entry->hwTimestamp, entry->values);
1434 mLock.lock();
1435}
1436
1437void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1438 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1439#if DEBUG_OUTBOUND_EVENT_DETAILS
1440 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1441 "source=0x%x, sensorType=%s",
1442 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001443 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001444#endif
1445 std::unique_ptr<CommandEntry> commandEntry =
1446 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1447 commandEntry->sensorEntry = entry;
1448 postCommandLocked(std::move(commandEntry));
1449}
1450
1451bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1452#if DEBUG_OUTBOUND_EVENT_DETAILS
1453 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1454 NamedEnum::string(sensorType).c_str());
1455#endif
1456 { // acquire lock
1457 std::scoped_lock _l(mLock);
1458
1459 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1460 std::shared_ptr<EventEntry> entry = *it;
1461 if (entry->type == EventEntry::Type::SENSOR) {
1462 it = mInboundQueue.erase(it);
1463 releaseInboundEventLocked(entry);
1464 }
1465 }
1466 }
1467 return true;
1468}
1469
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001470bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001471 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001472 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001474 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 entry->dispatchInProgress = true;
1476
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001477 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479
1480 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001481 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001482 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001483 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1484 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 return true;
1486 }
1487
1488 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1489
1490 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001491 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492
1493 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001494 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 if (isPointerEvent) {
1496 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001497 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001498 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001499 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 } else {
1501 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001502 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001503 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001505 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 return false;
1507 }
1508
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001509 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001510 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001511 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1512 return true;
1513 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001514 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001515 CancelationOptions::Mode mode(isPointerEvent
1516 ? CancelationOptions::CANCEL_POINTER_EVENTS
1517 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1518 CancelationOptions options(mode, "input event injection failed");
1519 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 return true;
1521 }
1522
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001523 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001524 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001526 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001527 std::unordered_map<int32_t, TouchState>::iterator it =
1528 mTouchStatesByDisplay.find(entry->displayId);
1529 if (it != mTouchStatesByDisplay.end()) {
1530 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001531 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001532 // The event has gone through these portal windows, so we add monitoring targets of
1533 // the corresponding displays as well.
1534 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001535 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001536 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001537 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001538 }
1539 }
1540 }
1541 }
1542
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 // Dispatch the motion.
1544 if (conflictingPointerActions) {
1545 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001546 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 synthesizeCancelationEventsForAllConnectionsLocked(options);
1548 }
1549 dispatchEventLocked(currentTime, entry, inputTargets);
1550 return true;
1551}
1552
arthurhungb89ccb02020-12-30 16:19:01 +08001553void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1554 bool isExiting, const MotionEntry& motionEntry) {
1555 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1556 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1557 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1558 PointerCoords pointerCoords;
1559 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1560 pointerCoords.transform(windowHandle->getInfo()->transform);
1561
1562 std::unique_ptr<DragEntry> dragEntry =
1563 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1564 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1565 pointerCoords.getY());
1566
1567 enqueueInboundEventLocked(std::move(dragEntry));
1568}
1569
1570void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1571 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1572 if (channel == nullptr) {
1573 return; // Window has gone away
1574 }
1575 InputTarget target;
1576 target.inputChannel = channel;
1577 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1578 entry->dispatchInProgress = true;
1579 dispatchEventLocked(currentTime, entry, {target});
1580}
1581
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001582void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001584 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001585 ", policyFlags=0x%x, "
1586 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1587 "metaState=0x%x, buttonState=0x%x,"
1588 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001589 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1590 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1591 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001593 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001595 "x=%f, y=%f, pressure=%f, size=%f, "
1596 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1597 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001598 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1599 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1600 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1601 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1602 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1603 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1604 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1605 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1606 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1607 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 }
1609#endif
1610}
1611
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001612void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1613 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001615 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616#if DEBUG_DISPATCH_CYCLE
1617 ALOGD("dispatchEventToCurrentInputTargets");
1618#endif
1619
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001620 updateInteractionTokensLocked(*eventEntry, inputTargets);
1621
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1623
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001624 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001626 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001627 sp<Connection> connection =
1628 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001629 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001630 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001632 if (DEBUG_FOCUS) {
1633 ALOGD("Dropping event delivery to target with channel '%s' because it "
1634 "is no longer registered with the input dispatcher.",
1635 inputTarget.inputChannel->getName().c_str());
1636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 }
1638 }
1639}
1640
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001641void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1642 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1643 // If the policy decides to close the app, we will get a channel removal event via
1644 // unregisterInputChannel, and will clean up the connection that way. We are already not
1645 // sending new pointers to the connection when it blocked, but focused events will continue to
1646 // pile up.
1647 ALOGW("Canceling events for %s because it is unresponsive",
1648 connection->inputChannel->getName().c_str());
1649 if (connection->status == Connection::STATUS_NORMAL) {
1650 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1651 "application not responding");
1652 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 }
1654}
1655
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001656void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001657 if (DEBUG_FOCUS) {
1658 ALOGD("Resetting ANR timeouts.");
1659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660
1661 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001662 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001663 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664}
1665
Tiger Huang721e26f2018-07-24 22:26:19 +08001666/**
1667 * Get the display id that the given event should go to. If this event specifies a valid display id,
1668 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1669 * Focused display is the display that the user most recently interacted with.
1670 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001671int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001672 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001673 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001674 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1676 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001677 break;
1678 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001679 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001680 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1681 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001682 break;
1683 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001684 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001685 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001686 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001687 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001688 case EventEntry::Type::SENSOR:
1689 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001690 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001691 return ADISPLAY_ID_NONE;
1692 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001693 }
1694 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1695}
1696
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001697bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1698 const char* focusedWindowName) {
1699 if (mAnrTracker.empty()) {
1700 // already processed all events that we waited for
1701 mKeyIsWaitingForEventsTimeout = std::nullopt;
1702 return false;
1703 }
1704
1705 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1706 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001707 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001708 mKeyIsWaitingForEventsTimeout = currentTime +
1709 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1710 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001711 return true;
1712 }
1713
1714 // We still have pending events, and already started the timer
1715 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1716 return true; // Still waiting
1717 }
1718
1719 // Waited too long, and some connection still hasn't processed all motions
1720 // Just send the key to the focused window
1721 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1722 focusedWindowName);
1723 mKeyIsWaitingForEventsTimeout = std::nullopt;
1724 return false;
1725}
1726
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001727InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1728 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1729 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001730 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731
Tiger Huang721e26f2018-07-24 22:26:19 +08001732 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001733 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001734 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001735 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1736
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 // If there is no currently focused window and no focused application
1738 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001739 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1740 ALOGI("Dropping %s event because there is no focused window or focused application in "
1741 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001742 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001743 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
1745
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001746 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1747 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1748 // start interacting with another application via touch (app switch). This code can be removed
1749 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1750 // an app is expected to have a focused window.
1751 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1752 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1753 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001754 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1755 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1756 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001758 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001759 ALOGW("Waiting because no window has focus but %s may eventually add a "
1760 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001761 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001762 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001763 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001764 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1765 // Already raised ANR. Drop the event
1766 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001767 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001768 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001769 } else {
1770 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001771 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772 }
1773 }
1774
1775 // we have a valid, non-null focused window
1776 resetNoFocusedWindowTimeoutLocked();
1777
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001779 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001780 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 }
1782
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001783 if (focusedWindowHandle->getInfo()->paused) {
1784 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001785 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001786 }
1787
1788 // If the event is a key event, then we must wait for all previous events to
1789 // complete before delivering it because previous events may have the
1790 // side-effect of transferring focus to a different window and we want to
1791 // ensure that the following keys are sent to the new window.
1792 //
1793 // Suppose the user touches a button in a window then immediately presses "A".
1794 // If the button causes a pop-up window to appear then we want to ensure that
1795 // the "A" key is delivered to the new pop-up window. This is because users
1796 // often anticipate pending UI changes when typing on a keyboard.
1797 // To obtain this behavior, we must serialize key events with respect to all
1798 // prior input events.
1799 if (entry.type == EventEntry::Type::KEY) {
1800 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1801 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001802 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 }
1805
1806 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001807 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1809 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810
1811 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001812 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813}
1814
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001815/**
1816 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1817 * that are currently unresponsive.
1818 */
1819std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1820 const std::vector<TouchedMonitor>& monitors) const {
1821 std::vector<TouchedMonitor> responsiveMonitors;
1822 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1823 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1824 sp<Connection> connection = getConnectionLocked(
1825 monitor.monitor.inputChannel->getConnectionToken());
1826 if (connection == nullptr) {
1827 ALOGE("Could not find connection for monitor %s",
1828 monitor.monitor.inputChannel->getName().c_str());
1829 return false;
1830 }
1831 if (!connection->responsive) {
1832 ALOGW("Unresponsive monitor %s will not get the new gesture",
1833 connection->inputChannel->getName().c_str());
1834 return false;
1835 }
1836 return true;
1837 });
1838 return responsiveMonitors;
1839}
1840
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001841InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1842 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1843 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001844 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 enum InjectionPermission {
1846 INJECTION_PERMISSION_UNKNOWN,
1847 INJECTION_PERMISSION_GRANTED,
1848 INJECTION_PERMISSION_DENIED
1849 };
1850
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 // For security reasons, we defer updating the touch state until we are sure that
1852 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001853 int32_t displayId = entry.displayId;
1854 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1856
1857 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001860 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1861 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001863 // Copy current touch state into tempTouchState.
1864 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1865 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001866 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001868 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1869 mTouchStatesByDisplay.find(displayId);
1870 if (oldStateIt != mTouchStatesByDisplay.end()) {
1871 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001872 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001873 }
1874
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001875 bool isSplit = tempTouchState.split;
1876 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1877 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1878 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001879 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1880 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1881 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1882 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1883 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001884 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 bool wrongDevice = false;
1886 if (newGesture) {
1887 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001888 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001889 ALOGI("Dropping event because a pointer for a different device is already down "
1890 "in display %" PRId32,
1891 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001892 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 switchedDevice = false;
1895 wrongDevice = true;
1896 goto Failed;
1897 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001898 tempTouchState.reset();
1899 tempTouchState.down = down;
1900 tempTouchState.deviceId = entry.deviceId;
1901 tempTouchState.source = entry.source;
1902 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001904 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001905 ALOGI("Dropping move event because a pointer for a different device is already active "
1906 "in display %" PRId32,
1907 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001908 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001910 switchedDevice = false;
1911 wrongDevice = true;
1912 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 }
1914
1915 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1916 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1917
Garfield Tan00f511d2019-06-12 16:55:40 -07001918 int32_t x;
1919 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001921 // Always dispatch mouse events to cursor position.
1922 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001923 x = int32_t(entry.xCursorPosition);
1924 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001925 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001926 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1927 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001928 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001929 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001930 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001931 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1932 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001933
1934 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001935 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001936 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001939 if (newTouchedWindowHandle != nullptr &&
1940 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001941 // New window supports splitting, but we should never split mouse events.
1942 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 } else if (isSplit) {
1944 // New window does not support splitting but we have already split events.
1945 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001946 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 }
1948
1949 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001950 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001953 }
1954
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001955 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1956 ALOGI("Not sending touch event to %s because it is paused",
1957 newTouchedWindowHandle->getName().c_str());
1958 newTouchedWindowHandle = nullptr;
1959 }
1960
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001961 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001963 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1964 if (!isResponsive) {
1965 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001966 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1967 newTouchedWindowHandle = nullptr;
1968 }
1969 }
1970
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001971 // Drop events that can't be trusted due to occlusion
1972 if (newTouchedWindowHandle != nullptr &&
1973 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1974 TouchOcclusionInfo occlusionInfo =
1975 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001976 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001977 if (DEBUG_TOUCH_OCCLUSION) {
1978 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1979 for (const auto& log : occlusionInfo.debugInfo) {
1980 ALOGD("%s", log.c_str());
1981 }
1982 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001983 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1984 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1985 ALOGW("Dropping untrusted touch event due to %s/%d",
1986 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1987 newTouchedWindowHandle = nullptr;
1988 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001989 }
1990 }
1991
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001992 // Also don't send the new touch event to unresponsive gesture monitors
1993 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1994
Michael Wright3dd60e22019-03-27 22:06:44 +00001995 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1996 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001997 "(%d, %d) in display %" PRId32 ".",
1998 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001999 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 goto Failed;
2001 }
2002
2003 if (newTouchedWindowHandle != nullptr) {
2004 // Set target flags.
2005 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2006 if (isSplit) {
2007 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002009 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2010 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2011 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2012 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2013 }
2014
2015 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002016 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2017 newHoverWindowHandle = nullptr;
2018 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002019 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002020 }
2021
2022 // Update the temporary touch state.
2023 BitSet32 pointerIds;
2024 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002025 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002026 pointerIds.markBit(pointerId);
2027 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002028 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 }
2030
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002031 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 } else {
2033 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2034
2035 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002036 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002037 if (DEBUG_FOCUS) {
2038 ALOGD("Dropping event because the pointer is not down or we previously "
2039 "dropped the pointer down event in display %" PRId32,
2040 displayId);
2041 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002042 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 goto Failed;
2044 }
2045
arthurhung6d4bed92021-03-17 11:59:33 +08002046 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002047
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002049 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002050 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002051 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2052 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053
2054 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002055 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002056 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2058 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002059 if (DEBUG_FOCUS) {
2060 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2061 oldTouchedWindowHandle->getName().c_str(),
2062 newTouchedWindowHandle->getName().c_str(), displayId);
2063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2066 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2067 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068
2069 // Make a slippery entrance into the new window.
2070 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2071 isSplit = true;
2072 }
2073
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074 int32_t targetFlags =
2075 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 if (isSplit) {
2077 targetFlags |= InputTarget::FLAG_SPLIT;
2078 }
2079 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2080 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002081 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2082 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 }
2084
2085 BitSet32 pointerIds;
2086 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002087 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002089 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091 }
2092 }
2093
2094 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002095 // Let the previous window know that the hover sequence is over, unless we already did it
2096 // when dispatching it as is to newTouchedWindowHandle.
2097 if (mLastHoverWindowHandle != nullptr &&
2098 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2099 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100#if DEBUG_HOVER
2101 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002102 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002104 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2105 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
2107
Garfield Tandf26e862020-07-01 20:18:19 -07002108 // Let the new window know that the hover sequence is starting, unless we already did it
2109 // when dispatching it as is to newTouchedWindowHandle.
2110 if (newHoverWindowHandle != nullptr &&
2111 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2112 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113#if DEBUG_HOVER
2114 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002115 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002117 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2118 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2119 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
2121 }
2122
2123 // Check permission to inject into all touched foreground windows and ensure there
2124 // is at least one touched foreground window.
2125 {
2126 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2129 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002130 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002131 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 injectionPermission = INJECTION_PERMISSION_DENIED;
2133 goto Failed;
2134 }
2135 }
2136 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002137 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002138 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002139 ALOGI("Dropping event because there is no touched foreground window in display "
2140 "%" PRId32 " or gesture monitor to receive it.",
2141 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002142 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 goto Failed;
2144 }
2145
2146 // Permission granted to injection into all touched foreground windows.
2147 injectionPermission = INJECTION_PERMISSION_GRANTED;
2148 }
2149
2150 // Check whether windows listening for outside touches are owned by the same UID. If it is
2151 // set the policy flag that we will not reveal coordinate information to this window.
2152 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2153 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002154 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002155 if (foregroundWindowHandle) {
2156 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002157 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002158 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2159 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2160 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002161 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2162 InputTarget::FLAG_ZERO_COORDS,
2163 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166 }
2167 }
2168 }
2169
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 // If this is the first pointer going down and the touched window has a wallpaper
2171 // then also add the touched wallpaper windows so they are locked in for the duration
2172 // of the touch gesture.
2173 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2174 // engine only supports touch events. We would need to add a mechanism similar
2175 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2176 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2177 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002180 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002181 getWindowHandlesLocked(displayId);
2182 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002184 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002185 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002186 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002187 .addOrUpdateWindow(windowHandle,
2188 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2189 InputTarget::
2190 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2191 InputTarget::FLAG_DISPATCH_AS_IS,
2192 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
2194 }
2195 }
2196 }
2197
2198 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002199 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002201 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002203 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 }
2205
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002206 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002207 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002208 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002209 }
2210
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 // Drop the outside or hover touch windows since we will not care about them
2212 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214
2215Failed:
2216 // Check injection permission once and for all.
2217 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002218 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 injectionPermission = INJECTION_PERMISSION_GRANTED;
2220 } else {
2221 injectionPermission = INJECTION_PERMISSION_DENIED;
2222 }
2223 }
2224
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002225 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2226 return injectionResult;
2227 }
2228
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002230 if (!wrongDevice) {
2231 if (switchedDevice) {
2232 if (DEBUG_FOCUS) {
2233 ALOGD("Conflicting pointer actions: Switched to a different device.");
2234 }
2235 *outConflictingPointerActions = true;
2236 }
2237
2238 if (isHoverAction) {
2239 // Started hovering, therefore no longer down.
2240 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002241 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002242 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2243 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 *outConflictingPointerActions = true;
2246 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002247 tempTouchState.reset();
2248 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2249 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2250 tempTouchState.deviceId = entry.deviceId;
2251 tempTouchState.source = entry.source;
2252 tempTouchState.displayId = displayId;
2253 }
2254 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2255 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2256 // All pointers up or canceled.
2257 tempTouchState.reset();
2258 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2259 // First pointer went down.
2260 if (oldState && oldState->down) {
2261 if (DEBUG_FOCUS) {
2262 ALOGD("Conflicting pointer actions: Down received while already down.");
2263 }
2264 *outConflictingPointerActions = true;
2265 }
2266 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2267 // One pointer went up.
2268 if (isSplit) {
2269 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2270 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002272 for (size_t i = 0; i < tempTouchState.windows.size();) {
2273 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2274 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2275 touchedWindow.pointerIds.clearBit(pointerId);
2276 if (touchedWindow.pointerIds.isEmpty()) {
2277 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2278 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002281 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002283 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002284 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002285
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002286 // Save changes unless the action was scroll in which case the temporary touch
2287 // state was only valid for this one action.
2288 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2289 if (tempTouchState.displayId >= 0) {
2290 mTouchStatesByDisplay[displayId] = tempTouchState;
2291 } else {
2292 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002296 // Update hover state.
2297 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
2299
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 return injectionResult;
2301}
2302
arthurhung6d4bed92021-03-17 11:59:33 +08002303void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2304 const sp<InputWindowHandle> dropWindow =
2305 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2306 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2307 true /*ignoreDragWindow*/);
2308 if (dropWindow) {
2309 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2310 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002311 } else {
2312 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002313 }
2314 mDragState.reset();
2315}
2316
2317void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2318 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002319 return;
2320 }
2321
arthurhung6d4bed92021-03-17 11:59:33 +08002322 if (!mDragState->isStartDrag) {
2323 mDragState->isStartDrag = true;
2324 mDragState->isStylusButtonDownAtStart =
2325 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2326 }
2327
arthurhungb89ccb02020-12-30 16:19:01 +08002328 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2329 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2330 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2331 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002332 // Handle the special case : stylus button no longer pressed.
2333 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2334 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2335 finishDragAndDrop(entry.displayId, x, y);
2336 return;
2337 }
2338
arthurhungb89ccb02020-12-30 16:19:01 +08002339 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002340 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002341 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2342 true /*ignoreDragWindow*/);
2343 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002344 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2345 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2346 if (mDragState->dragHoverWindowHandle != nullptr) {
2347 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2348 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002349 }
arthurhung6d4bed92021-03-17 11:59:33 +08002350 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002351 }
2352 // enqueue drag location if needed.
2353 if (hoverWindowHandle != nullptr) {
2354 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2355 }
arthurhung6d4bed92021-03-17 11:59:33 +08002356 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2357 finishDragAndDrop(entry.displayId, x, y);
2358 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002359 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002360 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002361 }
2362}
2363
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002365 int32_t targetFlags, BitSet32 pointerIds,
2366 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002367 std::vector<InputTarget>::iterator it =
2368 std::find_if(inputTargets.begin(), inputTargets.end(),
2369 [&windowHandle](const InputTarget& inputTarget) {
2370 return inputTarget.inputChannel->getConnectionToken() ==
2371 windowHandle->getToken();
2372 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002373
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002374 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002375
2376 if (it == inputTargets.end()) {
2377 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002378 std::shared_ptr<InputChannel> inputChannel =
2379 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002380 if (inputChannel == nullptr) {
2381 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2382 return;
2383 }
2384 inputTarget.inputChannel = inputChannel;
2385 inputTarget.flags = targetFlags;
2386 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002387 inputTarget.displaySize =
2388 vec2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002389 inputTargets.push_back(inputTarget);
2390 it = inputTargets.end() - 1;
2391 }
2392
2393 ALOG_ASSERT(it->flags == targetFlags);
2394 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2395
chaviw1ff3d1e2020-07-01 15:53:47 -07002396 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397}
2398
Michael Wright3dd60e22019-03-27 22:06:44 +00002399void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002400 int32_t displayId, float xOffset,
2401 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002402 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2403 mGlobalMonitorsByDisplay.find(displayId);
2404
2405 if (it != mGlobalMonitorsByDisplay.end()) {
2406 const std::vector<Monitor>& monitors = it->second;
2407 for (const Monitor& monitor : monitors) {
2408 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
2411}
2412
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2414 float yOffset,
2415 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002416 InputTarget target;
2417 target.inputChannel = monitor.inputChannel;
2418 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002419 ui::Transform t;
2420 t.set(xOffset, yOffset);
2421 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002422 inputTargets.push_back(target);
2423}
2424
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002426 const InjectionState* injectionState) {
2427 if (injectionState &&
2428 (windowHandle == nullptr ||
2429 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2430 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002431 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002433 "owned by uid %d",
2434 injectionState->injectorPid, injectionState->injectorUid,
2435 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 } else {
2437 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002438 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
2440 return false;
2441 }
2442 return true;
2443}
2444
Robert Carrc9bf1d32020-04-13 17:21:08 -07002445/**
2446 * Indicate whether one window handle should be considered as obscuring
2447 * another window handle. We only check a few preconditions. Actually
2448 * checking the bounds is left to the caller.
2449 */
2450static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2451 const sp<InputWindowHandle>& otherHandle) {
2452 // Compare by token so cloned layers aren't counted
2453 if (haveSameToken(windowHandle, otherHandle)) {
2454 return false;
2455 }
2456 auto info = windowHandle->getInfo();
2457 auto otherInfo = otherHandle->getInfo();
2458 if (!otherInfo->visible) {
2459 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002460 } else if (otherInfo->alpha == 0 &&
2461 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2462 // Those act as if they were invisible, so we don't need to flag them.
2463 // We do want to potentially flag touchable windows even if they have 0
2464 // opacity, since they can consume touches and alter the effects of the
2465 // user interaction (eg. apps that rely on
2466 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2467 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2468 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002469 } else if (info->ownerUid == otherInfo->ownerUid) {
2470 // If ownerUid is the same we don't generate occlusion events as there
2471 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002472 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002473 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002474 return false;
2475 } else if (otherInfo->displayId != info->displayId) {
2476 return false;
2477 }
2478 return true;
2479}
2480
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002481/**
2482 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2483 * untrusted, one should check:
2484 *
2485 * 1. If result.hasBlockingOcclusion is true.
2486 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2487 * BLOCK_UNTRUSTED.
2488 *
2489 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2490 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2491 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2492 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2493 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2494 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2495 *
2496 * If neither of those is true, then it means the touch can be allowed.
2497 */
2498InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2499 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002500 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2501 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002502 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2503 TouchOcclusionInfo info;
2504 info.hasBlockingOcclusion = false;
2505 info.obscuringOpacity = 0;
2506 info.obscuringUid = -1;
2507 std::map<int32_t, float> opacityByUid;
2508 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2509 if (windowHandle == otherHandle) {
2510 break; // All future windows are below us. Exit early.
2511 }
2512 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002513 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2514 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002515 if (DEBUG_TOUCH_OCCLUSION) {
2516 info.debugInfo.push_back(
2517 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2518 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002519 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2520 // we perform the checks below to see if the touch can be propagated or not based on the
2521 // window's touch occlusion mode
2522 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2523 info.hasBlockingOcclusion = true;
2524 info.obscuringUid = otherInfo->ownerUid;
2525 info.obscuringPackage = otherInfo->packageName;
2526 break;
2527 }
2528 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2529 uint32_t uid = otherInfo->ownerUid;
2530 float opacity =
2531 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2532 // Given windows A and B:
2533 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2534 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2535 opacityByUid[uid] = opacity;
2536 if (opacity > info.obscuringOpacity) {
2537 info.obscuringOpacity = opacity;
2538 info.obscuringUid = uid;
2539 info.obscuringPackage = otherInfo->packageName;
2540 }
2541 }
2542 }
2543 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002544 if (DEBUG_TOUCH_OCCLUSION) {
2545 info.debugInfo.push_back(
2546 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2547 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002548 return info;
2549}
2550
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002551std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2552 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002553 return StringPrintf(INDENT2
2554 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2555 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2556 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2557 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002558 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002559 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002560 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002561 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2562 info->frameTop, info->frameRight, info->frameBottom,
2563 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002564 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2565 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2566 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002567}
2568
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002569bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2570 if (occlusionInfo.hasBlockingOcclusion) {
2571 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2572 occlusionInfo.obscuringUid);
2573 return false;
2574 }
2575 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2576 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2577 "%.2f, maximum allowed = %.2f)",
2578 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2579 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2580 return false;
2581 }
2582 return true;
2583}
2584
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2586 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002588 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002589 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002590 if (windowHandle == otherHandle) {
2591 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002594 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002595 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 return true;
2597 }
2598 }
2599 return false;
2600}
2601
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002602bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2603 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002604 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002605 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002606 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002607 if (windowHandle == otherHandle) {
2608 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002609 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002610 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002611 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002612 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002613 return true;
2614 }
2615 }
2616 return false;
2617}
2618
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002619std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002620 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002622 if (applicationHandle != nullptr) {
2623 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002624 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 } else {
2626 return applicationHandle->getName();
2627 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002628 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002629 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002631 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 }
2633}
2634
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002635void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002636 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002637 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2638 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002639 // Focus or pointer capture changed events are passed to apps, but do not represent user
2640 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002641 return;
2642 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002643 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002644 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002645 if (focusedWindowHandle != nullptr) {
2646 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002647 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002649 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650#endif
2651 return;
2652 }
2653 }
2654
2655 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002656 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002657 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002658 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2659 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 return;
2661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002663 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002664 eventType = USER_ACTIVITY_EVENT_TOUCH;
2665 }
2666 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002668 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002669 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2670 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002671 return;
2672 }
2673 eventType = USER_ACTIVITY_EVENT_BUTTON;
2674 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002676 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002677 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002678 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002679 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002680 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2681 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002682 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002683 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002684 break;
2685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 }
2687
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002688 std::unique_ptr<CommandEntry> commandEntry =
2689 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002690 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002692 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002693 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694}
2695
2696void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002697 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002698 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002699 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002700 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002702 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002703 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002704 ATRACE_NAME(message.c_str());
2705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706#if DEBUG_DISPATCH_CYCLE
2707 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002708 "globalScaleFactor=%f, pointerIds=0x%x %s",
2709 connection->getInputChannelName().c_str(), inputTarget.flags,
2710 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2711 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712#endif
2713
2714 // Skip this event if the connection status is not normal.
2715 // We don't want to enqueue additional outbound events if the connection is broken.
2716 if (connection->status != Connection::STATUS_NORMAL) {
2717#if DEBUG_DISPATCH_CYCLE
2718 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720#endif
2721 return;
2722 }
2723
2724 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002725 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2726 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2727 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002728 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002730 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002731 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002732 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002733 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 if (!splitMotionEntry) {
2735 return; // split event was dropped
2736 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002737 if (DEBUG_FOCUS) {
2738 ALOGD("channel '%s' ~ Split motion event.",
2739 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002740 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002741 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002742 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2743 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 return;
2745 }
2746 }
2747
2748 // Not splitting. Enqueue dispatch entries for the event as is.
2749 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2750}
2751
2752void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002754 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002755 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002756 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002757 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002758 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002759 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002760 ATRACE_NAME(message.c_str());
2761 }
2762
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002763 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764
2765 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002766 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002767 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002768 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002770 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002771 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002772 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002774 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002775 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002776 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778
2779 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002780 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 startDispatchCycleLocked(currentTime, connection);
2782 }
2783}
2784
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002786 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002787 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002788 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002789 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2791 connection->getInputChannelName().c_str(),
2792 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002793 ATRACE_NAME(message.c_str());
2794 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002795 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 if (!(inputTargetFlags & dispatchMode)) {
2797 return;
2798 }
2799 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2800
2801 // This is a new event.
2802 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002803 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002804 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002806 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2807 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002808 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002810 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002811 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002812 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002813 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002814 dispatchEntry->resolvedAction = keyEntry.action;
2815 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2818 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002820 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2821 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 return; // skip the inconsistent event
2824 }
2825 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002828 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002829 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002830 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2831 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2832 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2833 static_cast<int32_t>(IdGenerator::Source::OTHER);
2834 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2836 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2837 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2838 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2839 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2840 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2841 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2842 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2843 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2844 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2845 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002846 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002847 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848 }
2849 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002850 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2851 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002853 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2854 "event",
2855 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002860 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2862 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2863 }
2864 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2865 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002868 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2869 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2872 "event",
2873 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 return; // skip the inconsistent event
2876 }
2877
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002878 dispatchEntry->resolvedEventId =
2879 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2880 ? mIdGenerator.nextId()
2881 : motionEntry.id;
2882 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2883 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2884 ") to MotionEvent(id=0x%" PRIx32 ").",
2885 motionEntry.id, dispatchEntry->resolvedEventId);
2886 ATRACE_NAME(message.c_str());
2887 }
2888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002890 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891
2892 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002894 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002895 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2896 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002897 break;
2898 }
Chris Yef59a2f42020-10-16 12:55:26 -07002899 case EventEntry::Type::SENSOR: {
2900 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2901 break;
2902 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002903 case EventEntry::Type::CONFIGURATION_CHANGED:
2904 case EventEntry::Type::DEVICE_RESET: {
2905 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002906 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002907 break;
2908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 }
2910
2911 // Remember that we are waiting for this dispatch to complete.
2912 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002913 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 }
2915
2916 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002917 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002918 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002919}
2920
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002921/**
2922 * This function is purely for debugging. It helps us understand where the user interaction
2923 * was taking place. For example, if user is touching launcher, we will see a log that user
2924 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2925 * We will see both launcher and wallpaper in that list.
2926 * Once the interaction with a particular set of connections starts, no new logs will be printed
2927 * until the set of interacted connections changes.
2928 *
2929 * The following items are skipped, to reduce the logspam:
2930 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2931 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2932 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2933 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2934 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002935 */
2936void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2937 const std::vector<InputTarget>& targets) {
2938 // Skip ACTION_UP events, and all events other than keys and motions
2939 if (entry.type == EventEntry::Type::KEY) {
2940 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2941 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2942 return;
2943 }
2944 } else if (entry.type == EventEntry::Type::MOTION) {
2945 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2946 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2947 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2948 return;
2949 }
2950 } else {
2951 return; // Not a key or a motion
2952 }
2953
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07002954 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002955 std::vector<sp<Connection>> newConnections;
2956 for (const InputTarget& target : targets) {
2957 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2958 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2959 continue; // Skip windows that receive ACTION_OUTSIDE
2960 }
2961
2962 sp<IBinder> token = target.inputChannel->getConnectionToken();
2963 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002964 if (connection == nullptr) {
2965 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002966 }
2967 newConnectionTokens.insert(std::move(token));
2968 newConnections.emplace_back(connection);
2969 }
2970 if (newConnectionTokens == mInteractionConnectionTokens) {
2971 return; // no change
2972 }
2973 mInteractionConnectionTokens = newConnectionTokens;
2974
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002975 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002976 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002977 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002978 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002979 std::string message = "Interaction with: " + targetList;
2980 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002981 message += "<none>";
2982 }
2983 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2984}
2985
chaviwfd6d3512019-03-25 13:23:49 -07002986void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002987 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002988 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002989 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2990 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002991 return;
2992 }
2993
Vishnu Nairc519ff72021-01-21 08:23:08 -08002994 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002995 if (focusedToken == token) {
2996 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002997 return;
2998 }
2999
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003000 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3001 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003002 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003003 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004}
3005
3006void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003008 if (ATRACE_ENABLED()) {
3009 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003011 ATRACE_NAME(message.c_str());
3012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015#endif
3016
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003017 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3018 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003020 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003021 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003022 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023
3024 // Publish the event.
3025 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003026 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3027 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003028 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003029 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3030 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003033 status = connection->inputPublisher
3034 .publishKeyEvent(dispatchEntry->seq,
3035 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3036 keyEntry.source, keyEntry.displayId,
3037 std::move(hmac), dispatchEntry->resolvedAction,
3038 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3039 keyEntry.scanCode, keyEntry.metaState,
3040 keyEntry.repeatCount, keyEntry.downTime,
3041 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
3044
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003045 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003049 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050
chaviw82357092020-01-28 13:13:06 -08003051 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003052 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3054 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003055 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003056 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3057 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003058 // Don't apply window scale here since we don't want scale to affect raw
3059 // coordinates. The scale will be sent back to the client and applied
3060 // later when requesting relative coordinates.
3061 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3062 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003063 }
3064 usingCoords = scaledCoords;
3065 }
3066 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003067 // We don't want the dispatch target to know.
3068 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003069 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 scaledCoords[i].clear();
3071 }
3072 usingCoords = scaledCoords;
3073 }
3074 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003075
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003076 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077
3078 // Publish the motion event.
3079 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003080 .publishMotionEvent(dispatchEntry->seq,
3081 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003082 motionEntry.deviceId, motionEntry.source,
3083 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003084 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003085 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003087 motionEntry.edgeFlags, motionEntry.metaState,
3088 motionEntry.buttonState,
3089 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003090 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003091 motionEntry.xPrecision, motionEntry.yPrecision,
3092 motionEntry.xCursorPosition,
3093 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003094 dispatchEntry->displaySize.x,
3095 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003096 motionEntry.downTime, motionEntry.eventTime,
3097 motionEntry.pointerCount,
3098 motionEntry.pointerProperties, usingCoords);
3099 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 break;
3101 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003102
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003103 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003104 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003105 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003106 focusEntry.id,
3107 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003108 mInTouchMode);
3109 break;
3110 }
3111
Prabir Pradhan99987712020-11-10 18:43:05 -08003112 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3113 const auto& captureEntry =
3114 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3115 status = connection->inputPublisher
3116 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3117 captureEntry.pointerCaptureEnabled);
3118 break;
3119 }
3120
arthurhungb89ccb02020-12-30 16:19:01 +08003121 case EventEntry::Type::DRAG: {
3122 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3123 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3124 dragEntry.id, dragEntry.x,
3125 dragEntry.y,
3126 dragEntry.isExiting);
3127 break;
3128 }
3129
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003130 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003131 case EventEntry::Type::DEVICE_RESET:
3132 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003133 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003134 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137 }
3138
3139 // Check the result.
3140 if (status) {
3141 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003142 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 "This is unexpected because the wait queue is empty, so the pipe "
3145 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003146 "event to it, status=%s(%d)",
3147 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3148 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3150 } else {
3151 // Pipe is full and we are waiting for the app to finish process some events
3152 // before sending more events to it.
3153#if DEBUG_DISPATCH_CYCLE
3154 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 "waiting for the application to catch up",
3156 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
3159 } else {
3160 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003161 "status=%s(%d)",
3162 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3163 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3165 }
3166 return;
3167 }
3168
3169 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003170 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3171 connection->outboundQueue.end(),
3172 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003173 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003174 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003175 if (connection->responsive) {
3176 mAnrTracker.insert(dispatchEntry->timeoutTime,
3177 connection->inputChannel->getConnectionToken());
3178 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003179 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181}
3182
chaviw09c8d2d2020-08-24 15:48:26 -07003183std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3184 size_t size;
3185 switch (event.type) {
3186 case VerifiedInputEvent::Type::KEY: {
3187 size = sizeof(VerifiedKeyEvent);
3188 break;
3189 }
3190 case VerifiedInputEvent::Type::MOTION: {
3191 size = sizeof(VerifiedMotionEvent);
3192 break;
3193 }
3194 }
3195 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3196 return mHmacKeyManager.sign(start, size);
3197}
3198
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003199const std::array<uint8_t, 32> InputDispatcher::getSignature(
3200 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3201 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3202 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3203 // Only sign events up and down events as the purely move events
3204 // are tied to their up/down counterparts so signing would be redundant.
3205 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3206 verifiedEvent.actionMasked = actionMasked;
3207 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003208 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003209 }
3210 return INVALID_HMAC;
3211}
3212
3213const std::array<uint8_t, 32> InputDispatcher::getSignature(
3214 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3215 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3216 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3217 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003218 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003219}
3220
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003223 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224#if DEBUG_DISPATCH_CYCLE
3225 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227#endif
3228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 if (connection->status == Connection::STATUS_BROKEN ||
3230 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 return;
3232 }
3233
3234 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003235 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236}
3237
3238void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 const sp<Connection>& connection,
3240 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241#if DEBUG_DISPATCH_CYCLE
3242 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244#endif
3245
3246 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003247 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003248 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003249 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003250 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251
3252 // The connection appears to be unrecoverably broken.
3253 // Ignore already broken or zombie connections.
3254 if (connection->status == Connection::STATUS_NORMAL) {
3255 connection->status = Connection::STATUS_BROKEN;
3256
3257 if (notify) {
3258 // Notify other system components.
3259 onDispatchCycleBrokenLocked(currentTime, connection);
3260 }
3261 }
3262}
3263
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003264void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3265 while (!queue.empty()) {
3266 DispatchEntry* dispatchEntry = queue.front();
3267 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003268 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 }
3270}
3271
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003272void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 }
3276 delete dispatchEntry;
3277}
3278
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003279int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3280 std::scoped_lock _l(mLock);
3281 sp<Connection> connection = getConnectionLocked(connectionToken);
3282 if (connection == nullptr) {
3283 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3284 connectionToken.get(), events);
3285 return 0; // remove the callback
3286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003288 bool notify;
3289 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3290 if (!(events & ALOOPER_EVENT_INPUT)) {
3291 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3292 "events=0x%x",
3293 connection->getInputChannelName().c_str(), events);
3294 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 }
3296
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003297 nsecs_t currentTime = now();
3298 bool gotOne = false;
3299 status_t status = OK;
3300 for (;;) {
3301 Result<InputPublisher::ConsumerResponse> result =
3302 connection->inputPublisher.receiveConsumerResponse();
3303 if (!result.ok()) {
3304 status = result.error().code();
3305 break;
3306 }
3307
3308 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3309 const InputPublisher::Finished& finish =
3310 std::get<InputPublisher::Finished>(*result);
3311 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3312 finish.consumeTime);
3313 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
3314 // TODO(b/167947340): Report this data to LatencyTracker
3315 }
3316 gotOne = true;
3317 }
3318 if (gotOne) {
3319 runCommandsLockedInterruptible();
3320 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 return 1;
3322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323 }
3324
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003325 notify = status != DEAD_OBJECT || !connection->monitor;
3326 if (notify) {
3327 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3328 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3329 status);
3330 }
3331 } else {
3332 // Monitor channels are never explicitly unregistered.
3333 // We do it automatically when the remote endpoint is closed so don't warn about them.
3334 const bool stillHaveWindowHandle =
3335 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3336 notify = !connection->monitor && stillHaveWindowHandle;
3337 if (notify) {
3338 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3339 connection->getInputChannelName().c_str(), events);
3340 }
3341 }
3342
3343 // Remove the channel.
3344 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3345 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346}
3347
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003350 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003351 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 }
3353}
3354
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003356 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003357 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3358 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3359}
3360
3361void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3362 const CancelationOptions& options,
3363 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3364 for (const auto& it : monitorsByDisplay) {
3365 const std::vector<Monitor>& monitors = it.second;
3366 for (const Monitor& monitor : monitors) {
3367 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003368 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003369 }
3370}
3371
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003373 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003374 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003375 if (connection == nullptr) {
3376 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003378
3379 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380}
3381
3382void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3383 const sp<Connection>& connection, const CancelationOptions& options) {
3384 if (connection->status == Connection::STATUS_BROKEN) {
3385 return;
3386 }
3387
3388 nsecs_t currentTime = now();
3389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003390 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003391 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003393 if (cancelationEvents.empty()) {
3394 return;
3395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003397 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3398 "with reality: %s, mode=%d.",
3399 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3400 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003402
3403 InputTarget target;
3404 sp<InputWindowHandle> windowHandle =
3405 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3406 if (windowHandle != nullptr) {
3407 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003408 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003409 target.globalScaleFactor = windowInfo->globalScaleFactor;
3410 }
3411 target.inputChannel = connection->inputChannel;
3412 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3413
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003414 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003415 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003416 switch (cancelationEventEntry->type) {
3417 case EventEntry::Type::KEY: {
3418 logOutboundKeyDetails("cancel - ",
3419 static_cast<const KeyEntry&>(*cancelationEventEntry));
3420 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003422 case EventEntry::Type::MOTION: {
3423 logOutboundMotionDetails("cancel - ",
3424 static_cast<const MotionEntry&>(*cancelationEventEntry));
3425 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003427 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003428 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3429 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003430 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003431 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003432 break;
3433 }
3434 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003435 case EventEntry::Type::DEVICE_RESET:
3436 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003437 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003438 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003439 break;
3440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 }
3442
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003443 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3444 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003446
3447 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448}
3449
Svet Ganov5d3bc372020-01-26 23:11:07 -08003450void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3451 const sp<Connection>& connection) {
3452 if (connection->status == Connection::STATUS_BROKEN) {
3453 return;
3454 }
3455
3456 nsecs_t currentTime = now();
3457
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003458 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003459 connection->inputState.synthesizePointerDownEvents(currentTime);
3460
3461 if (downEvents.empty()) {
3462 return;
3463 }
3464
3465#if DEBUG_OUTBOUND_EVENT_DETAILS
3466 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3467 connection->getInputChannelName().c_str(), downEvents.size());
3468#endif
3469
3470 InputTarget target;
3471 sp<InputWindowHandle> windowHandle =
3472 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3473 if (windowHandle != nullptr) {
3474 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003475 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003476 target.globalScaleFactor = windowInfo->globalScaleFactor;
3477 }
3478 target.inputChannel = connection->inputChannel;
3479 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003481 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003482 switch (downEventEntry->type) {
3483 case EventEntry::Type::MOTION: {
3484 logOutboundMotionDetails("down - ",
3485 static_cast<const MotionEntry&>(*downEventEntry));
3486 break;
3487 }
3488
3489 case EventEntry::Type::KEY:
3490 case EventEntry::Type::FOCUS:
3491 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003492 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003493 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003494 case EventEntry::Type::SENSOR:
3495 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003496 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003497 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003498 break;
3499 }
3500 }
3501
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003502 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3503 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003504 }
3505
3506 startDispatchCycleLocked(currentTime, connection);
3507}
3508
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003509std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3510 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 ALOG_ASSERT(pointerIds.value != 0);
3512
3513 uint32_t splitPointerIndexMap[MAX_POINTERS];
3514 PointerProperties splitPointerProperties[MAX_POINTERS];
3515 PointerCoords splitPointerCoords[MAX_POINTERS];
3516
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003517 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 uint32_t splitPointerCount = 0;
3519
3520 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003521 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003523 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 uint32_t pointerId = uint32_t(pointerProperties.id);
3525 if (pointerIds.hasBit(pointerId)) {
3526 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3527 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3528 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003529 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 splitPointerCount += 1;
3531 }
3532 }
3533
3534 if (splitPointerCount != pointerIds.count()) {
3535 // This is bad. We are missing some of the pointers that we expected to deliver.
3536 // Most likely this indicates that we received an ACTION_MOVE events that has
3537 // different pointer ids than we expected based on the previous ACTION_DOWN
3538 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3539 // in this way.
3540 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003541 "we expected there to be %d pointers. This probably means we received "
3542 "a broken sequence of pointer ids from the input device.",
3543 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003544 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
3546
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003547 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003549 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3550 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3552 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003553 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 uint32_t pointerId = uint32_t(pointerProperties.id);
3555 if (pointerIds.hasBit(pointerId)) {
3556 if (pointerIds.count() == 1) {
3557 // The first/last pointer went down/up.
3558 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003559 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003560 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3561 ? AMOTION_EVENT_ACTION_CANCEL
3562 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 } else {
3564 // A secondary pointer went down/up.
3565 uint32_t splitPointerIndex = 0;
3566 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3567 splitPointerIndex += 1;
3568 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003569 action = maskedAction |
3570 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 }
3572 } else {
3573 // An unrelated pointer changed.
3574 action = AMOTION_EVENT_ACTION_MOVE;
3575 }
3576 }
3577
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003578 int32_t newId = mIdGenerator.nextId();
3579 if (ATRACE_ENABLED()) {
3580 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3581 ") to MotionEvent(id=0x%" PRIx32 ").",
3582 originalMotionEntry.id, newId);
3583 ATRACE_NAME(message.c_str());
3584 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003585 std::unique_ptr<MotionEntry> splitMotionEntry =
3586 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3587 originalMotionEntry.deviceId, originalMotionEntry.source,
3588 originalMotionEntry.displayId,
3589 originalMotionEntry.policyFlags, action,
3590 originalMotionEntry.actionButton,
3591 originalMotionEntry.flags, originalMotionEntry.metaState,
3592 originalMotionEntry.buttonState,
3593 originalMotionEntry.classification,
3594 originalMotionEntry.edgeFlags,
3595 originalMotionEntry.xPrecision,
3596 originalMotionEntry.yPrecision,
3597 originalMotionEntry.xCursorPosition,
3598 originalMotionEntry.yCursorPosition,
3599 originalMotionEntry.downTime, splitPointerCount,
3600 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003602 if (originalMotionEntry.injectionState) {
3603 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 splitMotionEntry->injectionState->refCount += 1;
3605 }
3606
3607 return splitMotionEntry;
3608}
3609
3610void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3611#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003612 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613#endif
3614
3615 bool needWake;
3616 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003617 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003619 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3620 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3621 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 } // release lock
3623
3624 if (needWake) {
3625 mLooper->wake();
3626 }
3627}
3628
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003629/**
3630 * If one of the meta shortcuts is detected, process them here:
3631 * Meta + Backspace -> generate BACK
3632 * Meta + Enter -> generate HOME
3633 * This will potentially overwrite keyCode and metaState.
3634 */
3635void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003636 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003637 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3638 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3639 if (keyCode == AKEYCODE_DEL) {
3640 newKeyCode = AKEYCODE_BACK;
3641 } else if (keyCode == AKEYCODE_ENTER) {
3642 newKeyCode = AKEYCODE_HOME;
3643 }
3644 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003645 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003646 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003647 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003648 keyCode = newKeyCode;
3649 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3650 }
3651 } else if (action == AKEY_EVENT_ACTION_UP) {
3652 // In order to maintain a consistent stream of up and down events, check to see if the key
3653 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3654 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003655 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003656 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003657 auto replacementIt = mReplacedKeys.find(replacement);
3658 if (replacementIt != mReplacedKeys.end()) {
3659 keyCode = replacementIt->second;
3660 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003661 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3662 }
3663 }
3664}
3665
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3667#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003668 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3669 "policyFlags=0x%x, action=0x%x, "
3670 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3671 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3672 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3673 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674#endif
3675 if (!validateKeyEvent(args->action)) {
3676 return;
3677 }
3678
3679 uint32_t policyFlags = args->policyFlags;
3680 int32_t flags = args->flags;
3681 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003682 // InputDispatcher tracks and generates key repeats on behalf of
3683 // whatever notifies it, so repeatCount should always be set to 0
3684 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3686 policyFlags |= POLICY_FLAG_VIRTUAL;
3687 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 if (policyFlags & POLICY_FLAG_FUNCTION) {
3690 metaState |= AMETA_FUNCTION_ON;
3691 }
3692
3693 policyFlags |= POLICY_FLAG_TRUSTED;
3694
Michael Wright78f24442014-08-06 15:55:28 -07003695 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003696 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003697
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003699 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003700 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3701 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702
Michael Wright2b3c3302018-03-02 17:19:13 +00003703 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003705 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3706 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003707 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 bool needWake;
3711 { // acquire lock
3712 mLock.lock();
3713
3714 if (shouldSendKeyToInputFilterLocked(args)) {
3715 mLock.unlock();
3716
3717 policyFlags |= POLICY_FLAG_FILTERED;
3718 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3719 return; // event was consumed by the filter
3720 }
3721
3722 mLock.lock();
3723 }
3724
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003725 std::unique_ptr<KeyEntry> newEntry =
3726 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3727 args->displayId, policyFlags, args->action, flags,
3728 keyCode, args->scanCode, metaState, repeatCount,
3729 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003731 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 mLock.unlock();
3733 } // release lock
3734
3735 if (needWake) {
3736 mLooper->wake();
3737 }
3738}
3739
3740bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3741 return mInputFilterEnabled;
3742}
3743
3744void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3745#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003746 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3747 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003748 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3749 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003750 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003751 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3752 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3753 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3754 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 for (uint32_t i = 0; i < args->pointerCount; i++) {
3756 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003757 "x=%f, y=%f, pressure=%f, size=%f, "
3758 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3759 "orientation=%f",
3760 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3761 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3762 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3763 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3764 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3765 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3766 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3767 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3768 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3769 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 }
3771#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003772 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3773 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 return;
3775 }
3776
3777 uint32_t policyFlags = args->policyFlags;
3778 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003779
3780 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003781 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003782 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3783 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003784 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786
3787 bool needWake;
3788 { // acquire lock
3789 mLock.lock();
3790
3791 if (shouldSendMotionToInputFilterLocked(args)) {
3792 mLock.unlock();
3793
3794 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003795 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003796 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3797 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003798 args->metaState, args->buttonState, args->classification, transform,
3799 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003800 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3801 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003802 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803
3804 policyFlags |= POLICY_FLAG_FILTERED;
3805 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3806 return; // event was consumed by the filter
3807 }
3808
3809 mLock.lock();
3810 }
3811
3812 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003813 std::unique_ptr<MotionEntry> newEntry =
3814 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3815 args->source, args->displayId, policyFlags,
3816 args->action, args->actionButton, args->flags,
3817 args->metaState, args->buttonState,
3818 args->classification, args->edgeFlags,
3819 args->xPrecision, args->yPrecision,
3820 args->xCursorPosition, args->yCursorPosition,
3821 args->downTime, args->pointerCount,
3822 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003824 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 mLock.unlock();
3826 } // release lock
3827
3828 if (needWake) {
3829 mLooper->wake();
3830 }
3831}
3832
Chris Yef59a2f42020-10-16 12:55:26 -07003833void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3834#if DEBUG_INBOUND_EVENT_DETAILS
3835 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3836 " sensorType=%s",
3837 args->id, args->eventTime, args->deviceId, args->source,
3838 NamedEnum::string(args->sensorType).c_str());
3839#endif
3840
3841 bool needWake;
3842 { // acquire lock
3843 mLock.lock();
3844
3845 // Just enqueue a new sensor event.
3846 std::unique_ptr<SensorEntry> newEntry =
3847 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3848 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3849 args->sensorType, args->accuracy,
3850 args->accuracyChanged, args->values);
3851
3852 needWake = enqueueInboundEventLocked(std::move(newEntry));
3853 mLock.unlock();
3854 } // release lock
3855
3856 if (needWake) {
3857 mLooper->wake();
3858 }
3859}
3860
Chris Yefb552902021-02-03 17:18:37 -08003861void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3862#if DEBUG_INBOUND_EVENT_DETAILS
3863 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3864 args->deviceId, args->isOn);
3865#endif
3866 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3867}
3868
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003870 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871}
3872
3873void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3874#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003875 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003876 "switchMask=0x%08x",
3877 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878#endif
3879
3880 uint32_t policyFlags = args->policyFlags;
3881 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003882 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883}
3884
3885void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3886#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003887 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3888 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889#endif
3890
3891 bool needWake;
3892 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003893 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003895 std::unique_ptr<DeviceResetEntry> newEntry =
3896 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3897 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 } // release lock
3899
3900 if (needWake) {
3901 mLooper->wake();
3902 }
3903}
3904
Prabir Pradhan7e186182020-11-10 13:56:45 -08003905void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3906#if DEBUG_INBOUND_EVENT_DETAILS
3907 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3908 args->enabled ? "true" : "false");
3909#endif
3910
Prabir Pradhan99987712020-11-10 18:43:05 -08003911 bool needWake;
3912 { // acquire lock
3913 std::scoped_lock _l(mLock);
3914 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3915 args->enabled);
3916 needWake = enqueueInboundEventLocked(std::move(entry));
3917 } // release lock
3918
3919 if (needWake) {
3920 mLooper->wake();
3921 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003922}
3923
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003924InputEventInjectionResult InputDispatcher::injectInputEvent(
3925 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3926 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927#if DEBUG_INBOUND_EVENT_DETAILS
3928 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003929 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3930 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003932 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933
3934 policyFlags |= POLICY_FLAG_INJECTED;
3935 if (hasInjectionPermission(injectorPid, injectorUid)) {
3936 policyFlags |= POLICY_FLAG_TRUSTED;
3937 }
3938
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003939 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003942 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3943 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003944 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003945 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003948 int32_t flags = incomingKey.getFlags();
3949 int32_t keyCode = incomingKey.getKeyCode();
3950 int32_t metaState = incomingKey.getMetaState();
3951 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003952 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003953 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003954 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003955 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3956 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3957 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003959 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3960 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003961 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962
3963 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3964 android::base::Timer t;
3965 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3966 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3967 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3968 std::to_string(t.duration().count()).c_str());
3969 }
3970 }
3971
3972 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003973 std::unique_ptr<KeyEntry> injectedEntry =
3974 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3975 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3976 incomingKey.getDisplayId(), policyFlags, action,
3977 flags, keyCode, incomingKey.getScanCode(), metaState,
3978 incomingKey.getRepeatCount(),
3979 incomingKey.getDownTime());
3980 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 }
3983
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003984 case AINPUT_EVENT_TYPE_MOTION: {
3985 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3986 int32_t action = motionEvent->getAction();
3987 size_t pointerCount = motionEvent->getPointerCount();
3988 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3989 int32_t actionButton = motionEvent->getActionButton();
3990 int32_t displayId = motionEvent->getDisplayId();
3991 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003992 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003993 }
3994
3995 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3996 nsecs_t eventTime = motionEvent->getEventTime();
3997 android::base::Timer t;
3998 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3999 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4000 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4001 std::to_string(t.duration().count()).c_str());
4002 }
4003 }
4004
4005 mLock.lock();
4006 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
4007 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004008 std::unique_ptr<MotionEntry> injectedEntry =
4009 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4010 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4011 motionEvent->getDisplayId(), policyFlags, action,
4012 actionButton, motionEvent->getFlags(),
4013 motionEvent->getMetaState(),
4014 motionEvent->getButtonState(),
4015 motionEvent->getClassification(),
4016 motionEvent->getEdgeFlags(),
4017 motionEvent->getXPrecision(),
4018 motionEvent->getYPrecision(),
4019 motionEvent->getRawXCursorPosition(),
4020 motionEvent->getRawYCursorPosition(),
4021 motionEvent->getDownTime(),
4022 uint32_t(pointerCount), pointerProperties,
4023 samplePointerCoords, motionEvent->getXOffset(),
4024 motionEvent->getYOffset());
4025 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004026 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
4027 sampleEventTimes += 1;
4028 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004029 std::unique_ptr<MotionEntry> nextInjectedEntry =
4030 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4031 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4032 motionEvent->getDisplayId(), policyFlags,
4033 action, actionButton, motionEvent->getFlags(),
4034 motionEvent->getMetaState(),
4035 motionEvent->getButtonState(),
4036 motionEvent->getClassification(),
4037 motionEvent->getEdgeFlags(),
4038 motionEvent->getXPrecision(),
4039 motionEvent->getYPrecision(),
4040 motionEvent->getRawXCursorPosition(),
4041 motionEvent->getRawYCursorPosition(),
4042 motionEvent->getDownTime(),
4043 uint32_t(pointerCount), pointerProperties,
4044 samplePointerCoords,
4045 motionEvent->getXOffset(),
4046 motionEvent->getYOffset());
4047 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 }
4049 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004053 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004054 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 }
4056
4057 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004058 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 injectionState->injectionIsAsync = true;
4060 }
4061
4062 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004063 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064
4065 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004066 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004067 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004068 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 }
4070
4071 mLock.unlock();
4072
4073 if (needWake) {
4074 mLooper->wake();
4075 }
4076
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004077 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004079 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004081 if (syncMode == InputEventInjectionSync::NONE) {
4082 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 } else {
4084 for (;;) {
4085 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004086 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 break;
4088 }
4089
4090 nsecs_t remainingTimeout = endTime - now();
4091 if (remainingTimeout <= 0) {
4092#if DEBUG_INJECTION
4093 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004096 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 break;
4098 }
4099
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004100 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 }
4102
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004103 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4104 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 while (injectionState->pendingForegroundDispatches != 0) {
4106#if DEBUG_INJECTION
4107 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004108 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109#endif
4110 nsecs_t remainingTimeout = endTime - now();
4111 if (remainingTimeout <= 0) {
4112#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4114 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004116 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 break;
4118 }
4119
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004120 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 }
4122 }
4123 }
4124
4125 injectionState->release();
4126 } // release lock
4127
4128#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004129 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131#endif
4132
4133 return injectionResult;
4134}
4135
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004136std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004137 std::array<uint8_t, 32> calculatedHmac;
4138 std::unique_ptr<VerifiedInputEvent> result;
4139 switch (event.getType()) {
4140 case AINPUT_EVENT_TYPE_KEY: {
4141 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4142 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4143 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004144 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004145 break;
4146 }
4147 case AINPUT_EVENT_TYPE_MOTION: {
4148 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4149 VerifiedMotionEvent verifiedMotionEvent =
4150 verifiedMotionEventFromMotionEvent(motionEvent);
4151 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004152 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004153 break;
4154 }
4155 default: {
4156 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4157 return nullptr;
4158 }
4159 }
4160 if (calculatedHmac == INVALID_HMAC) {
4161 return nullptr;
4162 }
4163 if (calculatedHmac != event.getHmac()) {
4164 return nullptr;
4165 }
4166 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004167}
4168
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 return injectorUid == 0 ||
4171 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172}
4173
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004174void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004175 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004176 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 if (injectionState) {
4178#if DEBUG_INJECTION
4179 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 "injectorPid=%d, injectorUid=%d",
4181 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182#endif
4183
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004184 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 // Log the outcome since the injector did not wait for the injection result.
4186 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004188 ALOGV("Asynchronous input event injection succeeded.");
4189 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004190 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004191 ALOGW("Asynchronous input event injection failed.");
4192 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004193 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004194 ALOGW("Asynchronous input event injection permission denied.");
4195 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004196 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 ALOGW("Asynchronous input event injection timed out.");
4198 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004199 case InputEventInjectionResult::PENDING:
4200 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4201 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 }
4203 }
4204
4205 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004206 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 }
4208}
4209
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004210void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4211 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 if (injectionState) {
4213 injectionState->pendingForegroundDispatches += 1;
4214 }
4215}
4216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004217void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4218 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 if (injectionState) {
4220 injectionState->pendingForegroundDispatches -= 1;
4221
4222 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004223 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 }
4225 }
4226}
4227
Vishnu Nairad321cd2020-08-20 16:40:21 -07004228const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004229 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004230 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4231 auto it = mWindowHandlesByDisplay.find(displayId);
4232 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004233}
4234
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004236 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004237 if (windowHandleToken == nullptr) {
4238 return nullptr;
4239 }
4240
Arthur Hungb92218b2018-08-14 12:00:21 +08004241 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004242 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004243 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004244 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004245 return windowHandle;
4246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
4248 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004249 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250}
4251
Vishnu Nairad321cd2020-08-20 16:40:21 -07004252sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4253 int displayId) const {
4254 if (windowHandleToken == nullptr) {
4255 return nullptr;
4256 }
4257
4258 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4259 if (windowHandle->getToken() == windowHandleToken) {
4260 return windowHandle;
4261 }
4262 }
4263 return nullptr;
4264}
4265
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004266sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4267 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004268 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004269 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004270 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004271 if (handle->getId() == windowHandle->getId() &&
4272 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004273 if (windowHandle->getInfo()->displayId != it.first) {
4274 ALOGE("Found window %s in display %" PRId32
4275 ", but it should belong to display %" PRId32,
4276 windowHandle->getName().c_str(), it.first,
4277 windowHandle->getInfo()->displayId);
4278 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004279 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 }
4282 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004283 return nullptr;
4284}
4285
4286sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4287 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4288 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289}
4290
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004291bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4292 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4293 const bool noInputChannel =
4294 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4295 if (connection != nullptr && noInputChannel) {
4296 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4297 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4298 return false;
4299 }
4300
4301 if (connection == nullptr) {
4302 if (!noInputChannel) {
4303 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4304 }
4305 return false;
4306 }
4307 if (!connection->responsive) {
4308 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4309 return false;
4310 }
4311 return true;
4312}
4313
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004314std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4315 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004316 auto connectionIt = mConnectionsByToken.find(token);
4317 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004318 return nullptr;
4319 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004320 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004321}
4322
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004323void InputDispatcher::updateWindowHandlesForDisplayLocked(
4324 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4325 if (inputWindowHandles.empty()) {
4326 // Remove all handles on a display if there are no windows left.
4327 mWindowHandlesByDisplay.erase(displayId);
4328 return;
4329 }
4330
4331 // Since we compare the pointer of input window handles across window updates, we need
4332 // to make sure the handle object for the same window stays unchanged across updates.
4333 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004334 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004335 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004336 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004337 }
4338
4339 std::vector<sp<InputWindowHandle>> newHandles;
4340 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4341 if (!handle->updateInfo()) {
4342 // handle no longer valid
4343 continue;
4344 }
4345
4346 const InputWindowInfo* info = handle->getInfo();
4347 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4348 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4349 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004350 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4351 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4352 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004353 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004354 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004355 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004356 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004357 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004358 }
4359
4360 if (info->displayId != displayId) {
4361 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4362 handle->getName().c_str(), displayId, info->displayId);
4363 continue;
4364 }
4365
Robert Carredd13602020-04-13 17:24:34 -07004366 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4367 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004368 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004369 oldHandle->updateFrom(handle);
4370 newHandles.push_back(oldHandle);
4371 } else {
4372 newHandles.push_back(handle);
4373 }
4374 }
4375
4376 // Insert or replace
4377 mWindowHandlesByDisplay[displayId] = newHandles;
4378}
4379
Arthur Hung72d8dc32020-03-28 00:48:39 +00004380void InputDispatcher::setInputWindows(
4381 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4382 { // acquire lock
4383 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004384 for (const auto& [displayId, handles] : handlesPerDisplay) {
4385 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004386 }
4387 }
4388 // Wake up poll loop since it may need to make new input dispatching choices.
4389 mLooper->wake();
4390}
4391
Arthur Hungb92218b2018-08-14 12:00:21 +08004392/**
4393 * Called from InputManagerService, update window handle list by displayId that can receive input.
4394 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4395 * If set an empty list, remove all handles from the specific display.
4396 * For focused handle, check if need to change and send a cancel event to previous one.
4397 * For removed handle, check if need to send a cancel event if already in touch.
4398 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004399void InputDispatcher::setInputWindowsLocked(
4400 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004401 if (DEBUG_FOCUS) {
4402 std::string windowList;
4403 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4404 windowList += iwh->getName() + " ";
4405 }
4406 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004409 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4410 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4411 const bool noInputWindow =
4412 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4413 if (noInputWindow && window->getToken() != nullptr) {
4414 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4415 window->getName().c_str());
4416 window->releaseChannel();
4417 }
4418 }
4419
Arthur Hung72d8dc32020-03-28 00:48:39 +00004420 // Copy old handles for release if they are no longer present.
4421 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422
Arthur Hung72d8dc32020-03-28 00:48:39 +00004423 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004424
Vishnu Nair958da932020-08-21 17:12:37 -07004425 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4426 if (mLastHoverWindowHandle &&
4427 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4428 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004429 mLastHoverWindowHandle = nullptr;
4430 }
4431
Vishnu Nairc519ff72021-01-21 08:23:08 -08004432 std::optional<FocusResolver::FocusChanges> changes =
4433 mFocusResolver.setInputWindows(displayId, windowHandles);
4434 if (changes) {
4435 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004438 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4439 mTouchStatesByDisplay.find(displayId);
4440 if (stateIt != mTouchStatesByDisplay.end()) {
4441 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004442 for (size_t i = 0; i < state.windows.size();) {
4443 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004444 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004445 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004446 ALOGD("Touched window was removed: %s in display %" PRId32,
4447 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004448 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004449 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004450 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4451 if (touchedInputChannel != nullptr) {
4452 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4453 "touched window was removed");
4454 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004456 state.windows.erase(state.windows.begin() + i);
4457 } else {
4458 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460 }
arthurhungb89ccb02020-12-30 16:19:01 +08004461
arthurhung6d4bed92021-03-17 11:59:33 +08004462 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004463 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004464 if (mDragState &&
4465 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004466 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004467 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004468 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004469 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004470
Arthur Hung72d8dc32020-03-28 00:48:39 +00004471 // Release information for windows that are no longer present.
4472 // This ensures that unused input channels are released promptly.
4473 // Otherwise, they might stick around until the window handle is destroyed
4474 // which might not happen until the next GC.
4475 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004476 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004477 if (DEBUG_FOCUS) {
4478 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004479 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004480 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004481 // To avoid making too many calls into the compat framework, only
4482 // check for window flags when windows are going away.
4483 // TODO(b/157929241) : delete this. This is only needed temporarily
4484 // in order to gather some data about the flag usage
4485 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4486 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4487 oldWindowHandle->getName().c_str());
4488 if (mCompatService != nullptr) {
4489 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4490 oldWindowHandle->getInfo()->ownerUid);
4491 }
4492 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004493 }
chaviw291d88a2019-02-14 10:33:58 -08004494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495}
4496
4497void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004498 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004499 if (DEBUG_FOCUS) {
4500 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4501 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4502 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004503 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505
Chris Yea209fde2020-07-22 13:54:51 -07004506 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004507 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004508
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004509 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4510 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004511 }
4512
Chris Yea209fde2020-07-22 13:54:51 -07004513 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004514 if (inputApplicationHandle != nullptr) {
4515 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4516 } else {
4517 mFocusedApplicationHandlesByDisplay.erase(displayId);
4518 }
4519
4520 // No matter what the old focused application was, stop waiting on it because it is
4521 // no longer focused.
4522 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 } // release lock
4524
4525 // Wake up poll loop since it may need to make new input dispatching choices.
4526 mLooper->wake();
4527}
4528
Tiger Huang721e26f2018-07-24 22:26:19 +08004529/**
4530 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4531 * the display not specified.
4532 *
4533 * We track any unreleased events for each window. If a window loses the ability to receive the
4534 * released event, we will send a cancel event to it. So when the focused display is changed, we
4535 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4536 * display. The display-specified events won't be affected.
4537 */
4538void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004539 if (DEBUG_FOCUS) {
4540 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4541 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004542 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004543 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004544
4545 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004546 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004547 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004548 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004549 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004550 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004551 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004552 CancelationOptions
4553 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4554 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004555 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004556 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4557 }
4558 }
4559 mFocusedDisplayId = displayId;
4560
Chris Ye3c2d6f52020-08-09 10:39:48 -07004561 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004562 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004563 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004564
Vishnu Nairad321cd2020-08-20 16:40:21 -07004565 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004566 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004567 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004568 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004569 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004570 }
4571 }
4572 }
4573
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004574 if (DEBUG_FOCUS) {
4575 logDispatchStateLocked();
4576 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004577 } // release lock
4578
4579 // Wake up poll loop since it may need to make new input dispatching choices.
4580 mLooper->wake();
4581}
4582
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004584 if (DEBUG_FOCUS) {
4585 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587
4588 bool changed;
4589 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004590 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
4592 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4593 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004594 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 }
4596
4597 if (mDispatchEnabled && !enabled) {
4598 resetAndDropEverythingLocked("dispatcher is being disabled");
4599 }
4600
4601 mDispatchEnabled = enabled;
4602 mDispatchFrozen = frozen;
4603 changed = true;
4604 } else {
4605 changed = false;
4606 }
4607
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004608 if (DEBUG_FOCUS) {
4609 logDispatchStateLocked();
4610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 } // release lock
4612
4613 if (changed) {
4614 // Wake up poll loop since it may need to make new input dispatching choices.
4615 mLooper->wake();
4616 }
4617}
4618
4619void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004620 if (DEBUG_FOCUS) {
4621 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623
4624 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004625 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626
4627 if (mInputFilterEnabled == enabled) {
4628 return;
4629 }
4630
4631 mInputFilterEnabled = enabled;
4632 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4633 } // release lock
4634
4635 // Wake up poll loop since there might be work to do to drop everything.
4636 mLooper->wake();
4637}
4638
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004639void InputDispatcher::setInTouchMode(bool inTouchMode) {
4640 std::scoped_lock lock(mLock);
4641 mInTouchMode = inTouchMode;
4642}
4643
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004644void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4645 if (opacity < 0 || opacity > 1) {
4646 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4647 return;
4648 }
4649
4650 std::scoped_lock lock(mLock);
4651 mMaximumObscuringOpacityForTouch = opacity;
4652}
4653
4654void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4655 std::scoped_lock lock(mLock);
4656 mBlockUntrustedTouchesMode = mode;
4657}
4658
arthurhungb89ccb02020-12-30 16:19:01 +08004659bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4660 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004661 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004662 if (DEBUG_FOCUS) {
4663 ALOGD("Trivial transfer to same window.");
4664 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004665 return true;
4666 }
4667
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004669 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670
chaviwfbe5d9c2018-12-26 12:23:37 -08004671 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4672 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004673 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004674 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 return false;
4676 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004677 if (DEBUG_FOCUS) {
4678 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4679 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004682 if (DEBUG_FOCUS) {
4683 ALOGD("Cannot transfer focus because windows are on different displays.");
4684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685 return false;
4686 }
4687
4688 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004689 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4690 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004691 for (size_t i = 0; i < state.windows.size(); i++) {
4692 const TouchedWindow& touchedWindow = state.windows[i];
4693 if (touchedWindow.windowHandle == fromWindowHandle) {
4694 int32_t oldTargetFlags = touchedWindow.targetFlags;
4695 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004697 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004699 int32_t newTargetFlags = oldTargetFlags &
4700 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4701 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004702 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
arthurhungb89ccb02020-12-30 16:19:01 +08004704 // Store the dragging window.
4705 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004706 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004707 }
4708
Jeff Brownf086ddb2014-02-11 14:28:48 -08004709 found = true;
4710 goto Found;
4711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 }
4713 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004714 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004716 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004717 if (DEBUG_FOCUS) {
4718 ALOGD("Focus transfer failed because from window did not have focus.");
4719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 return false;
4721 }
4722
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004723 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4724 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004725 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004726 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004727 CancelationOptions
4728 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4729 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004731 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 }
4733
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004734 if (DEBUG_FOCUS) {
4735 logDispatchStateLocked();
4736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 } // release lock
4738
4739 // Wake up poll loop since it may need to make new input dispatching choices.
4740 mLooper->wake();
4741 return true;
4742}
4743
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004744// Binder call
4745bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4746 sp<IBinder> fromToken;
4747 { // acquire lock
4748 std::scoped_lock _l(mLock);
4749
4750 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4751 if (toWindowHandle == nullptr) {
4752 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4753 return false;
4754 }
4755
4756 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4757
4758 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4759 if (touchStateIt == mTouchStatesByDisplay.end()) {
4760 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4761 displayId);
4762 return false;
4763 }
4764
4765 TouchState& state = touchStateIt->second;
4766 if (state.windows.size() != 1) {
4767 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4768 state.windows.size());
4769 return false;
4770 }
4771 const TouchedWindow& touchedWindow = state.windows[0];
4772 fromToken = touchedWindow.windowHandle->getToken();
4773 } // release lock
4774
4775 return transferTouchFocus(fromToken, destChannelToken);
4776}
4777
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004779 if (DEBUG_FOCUS) {
4780 ALOGD("Resetting and dropping all events (%s).", reason);
4781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782
4783 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4784 synthesizeCancelationEventsForAllConnectionsLocked(options);
4785
4786 resetKeyRepeatLocked();
4787 releasePendingEventLocked();
4788 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004789 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004792 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004794 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795}
4796
4797void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004798 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 dumpDispatchStateLocked(dump);
4800
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004801 std::istringstream stream(dump);
4802 std::string line;
4803
4804 while (std::getline(stream, line, '\n')) {
4805 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 }
4807}
4808
Prabir Pradhan99987712020-11-10 18:43:05 -08004809std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4810 std::string dump;
4811
4812 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4813 toString(mFocusedWindowRequestedPointerCapture));
4814
4815 std::string windowName = "None";
4816 if (mWindowTokenWithPointerCapture) {
4817 const sp<InputWindowHandle> captureWindowHandle =
4818 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4819 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4820 : "token has capture without window";
4821 }
4822 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4823
4824 return dump;
4825}
4826
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004827void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004828 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4829 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4830 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004831 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832
Tiger Huang721e26f2018-07-24 22:26:19 +08004833 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4834 dump += StringPrintf(INDENT "FocusedApplications:\n");
4835 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4836 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004837 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004838 const std::chrono::duration timeout =
4839 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004840 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004841 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004842 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004845 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004847
Vishnu Nairc519ff72021-01-21 08:23:08 -08004848 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004849 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004851 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004852 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004853 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4854 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004855 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004856 state.displayId, toString(state.down), toString(state.split),
4857 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004858 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004859 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004860 for (size_t i = 0; i < state.windows.size(); i++) {
4861 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004862 dump += StringPrintf(INDENT4
4863 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4864 i, touchedWindow.windowHandle->getName().c_str(),
4865 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004866 }
4867 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004868 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004869 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004870 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004871 dump += INDENT3 "Portal windows:\n";
4872 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004873 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004874 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4875 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004876 }
4877 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 }
4879 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004880 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 }
4882
arthurhung6d4bed92021-03-17 11:59:33 +08004883 if (mDragState) {
4884 dump += StringPrintf(INDENT "DragState:\n");
4885 mDragState->dump(dump, INDENT2);
4886 }
4887
Arthur Hungb92218b2018-08-14 12:00:21 +08004888 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004889 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004890 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004891 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004892 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004893 dump += INDENT2 "Windows:\n";
4894 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004895 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004896 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004898 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004899 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004900 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004901 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004902 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004903 "applicationInfo.name=%s, "
4904 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004905 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004906 i, windowInfo->name.c_str(), windowInfo->id,
4907 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004908 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004909 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004910 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004911 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004912 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004913 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004914 windowInfo->frameLeft, windowInfo->frameTop,
4915 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004916 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004917 windowInfo->applicationInfo.name.c_str(),
4918 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004919 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004920 dump += StringPrintf(", inputFeatures=%s",
4921 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004922 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004923 "ms, trustedOverlay=%s, hasToken=%s, "
4924 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004925 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004926 millis(windowInfo->dispatchingTimeout),
4927 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004928 toString(windowInfo->token != nullptr),
4929 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004930 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004931 }
4932 } else {
4933 dump += INDENT2 "Windows: <none>\n";
4934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 }
4936 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004937 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 }
4939
Michael Wright3dd60e22019-03-27 22:06:44 +00004940 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004941 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004942 const std::vector<Monitor>& monitors = it.second;
4943 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4944 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 }
4946 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004947 const std::vector<Monitor>& monitors = it.second;
4948 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4949 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004952 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 }
4954
4955 nsecs_t currentTime = now();
4956
4957 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004958 if (!mRecentQueue.empty()) {
4959 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004960 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004961 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004962 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004963 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964 }
4965 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004966 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 }
4968
4969 // Dump event currently being dispatched.
4970 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004971 dump += INDENT "PendingEvent:\n";
4972 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004973 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004974 dump += StringPrintf(", age=%" PRId64 "ms\n",
4975 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004977 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978 }
4979
4980 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004981 if (!mInboundQueue.empty()) {
4982 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004983 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004984 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004985 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004986 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987 }
4988 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004989 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 }
4991
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004992 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004993 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004994 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4995 const KeyReplacement& replacement = pair.first;
4996 int32_t newKeyCode = pair.second;
4997 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004998 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004999 }
5000 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005001 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005002 }
5003
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005004 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005005 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005006 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005007 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005008 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005009 connection->inputChannel->getFd().get(),
5010 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005011 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005012 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005014 if (!connection->outboundQueue.empty()) {
5015 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5016 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005017 dump += dumpQueue(connection->outboundQueue, currentTime);
5018
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005020 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 }
5022
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005023 if (!connection->waitQueue.empty()) {
5024 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5025 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005026 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005028 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 }
5030 }
5031 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005032 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033 }
5034
5035 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005036 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5037 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005039 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 }
5041
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005042 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005043 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5044 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5045 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046}
5047
Michael Wright3dd60e22019-03-27 22:06:44 +00005048void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5049 const size_t numMonitors = monitors.size();
5050 for (size_t i = 0; i < numMonitors; i++) {
5051 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005052 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005053 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5054 dump += "\n";
5055 }
5056}
5057
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005058class LooperEventCallback : public LooperCallback {
5059public:
5060 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5061 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5062
5063private:
5064 std::function<int(int events)> mCallback;
5065};
5066
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005067Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005068#if DEBUG_CHANNEL_CREATION
5069 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005070#endif
5071
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005072 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005073 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005074 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005075
5076 if (result) {
5077 return base::Error(result) << "Failed to open input channel pair with name " << name;
5078 }
5079
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005081 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005082 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005083 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005084 sp<Connection> connection =
5085 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005087 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5088 ALOGE("Created a new connection, but the token %p is already known", token.get());
5089 }
5090 mConnectionsByToken.emplace(token, connection);
5091
5092 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5093 this, std::placeholders::_1, token);
5094
5095 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 } // release lock
5097
5098 // Wake the looper because some connections have changed.
5099 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005100 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101}
5102
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005103Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5104 bool isGestureMonitor,
5105 const std::string& name,
5106 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005107 std::shared_ptr<InputChannel> serverChannel;
5108 std::unique_ptr<InputChannel> clientChannel;
5109 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5110 if (result) {
5111 return base::Error(result) << "Failed to open input channel pair with name " << name;
5112 }
5113
Michael Wright3dd60e22019-03-27 22:06:44 +00005114 { // acquire lock
5115 std::scoped_lock _l(mLock);
5116
5117 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005118 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5119 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005120 }
5121
Garfield Tan15601662020-09-22 15:32:38 -07005122 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005123 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005124 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005125
5126 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5127 ALOGE("Created a new connection, but the token %p is already known", token.get());
5128 }
5129 mConnectionsByToken.emplace(token, connection);
5130 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5131 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005133 auto& monitorsByDisplay =
5134 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005135 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005136
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005137 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005138 }
Garfield Tan15601662020-09-22 15:32:38 -07005139
Michael Wright3dd60e22019-03-27 22:06:44 +00005140 // Wake the looper because some connections have changed.
5141 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005142 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005143}
5144
Garfield Tan15601662020-09-22 15:32:38 -07005145status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005147 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148
Garfield Tan15601662020-09-22 15:32:38 -07005149 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 if (status) {
5151 return status;
5152 }
5153 } // release lock
5154
5155 // Wake the poll loop because removing the connection may have changed the current
5156 // synchronization state.
5157 mLooper->wake();
5158 return OK;
5159}
5160
Garfield Tan15601662020-09-22 15:32:38 -07005161status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5162 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005163 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005164 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005165 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 return BAD_VALUE;
5167 }
5168
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005170
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005172 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005175 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176
5177 nsecs_t currentTime = now();
5178 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5179
5180 connection->status = Connection::STATUS_ZOMBIE;
5181 return OK;
5182}
5183
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005184void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5185 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5186 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005187}
5188
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005189void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005190 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005191 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005192 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005193 std::vector<Monitor>& monitors = it->second;
5194 const size_t numMonitors = monitors.size();
5195 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005196 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005197 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5198 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005199 monitors.erase(monitors.begin() + i);
5200 break;
5201 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005202 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005203 if (monitors.empty()) {
5204 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005205 } else {
5206 ++it;
5207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208 }
5209}
5210
Michael Wright3dd60e22019-03-27 22:06:44 +00005211status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5212 { // acquire lock
5213 std::scoped_lock _l(mLock);
5214 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5215
5216 if (!foundDisplayId) {
5217 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5218 return BAD_VALUE;
5219 }
5220 int32_t displayId = foundDisplayId.value();
5221
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005222 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5223 mTouchStatesByDisplay.find(displayId);
5224 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005225 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5226 return BAD_VALUE;
5227 }
5228
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005229 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005230 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005231 std::optional<int32_t> foundDeviceId;
5232 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005233 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005234 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005235 foundDeviceId = state.deviceId;
5236 }
5237 }
5238 if (!foundDeviceId || !state.down) {
5239 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005240 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005241 return BAD_VALUE;
5242 }
5243 int32_t deviceId = foundDeviceId.value();
5244
5245 // Send cancel events to all the input channels we're stealing from.
5246 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005247 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005248 options.deviceId = deviceId;
5249 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005250 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005251 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005252 std::shared_ptr<InputChannel> channel =
5253 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005254 if (channel != nullptr) {
5255 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005256 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005257 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005258 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005259 canceledWindows += "]";
5260 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5261 canceledWindows.c_str());
5262
Michael Wright3dd60e22019-03-27 22:06:44 +00005263 // Then clear the current touch state so we stop dispatching to them as well.
5264 state.filterNonMonitors();
5265 }
5266 return OK;
5267}
5268
Prabir Pradhan99987712020-11-10 18:43:05 -08005269void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5270 { // acquire lock
5271 std::scoped_lock _l(mLock);
5272 if (DEBUG_FOCUS) {
5273 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5274 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5275 windowHandle != nullptr ? windowHandle->getName().c_str()
5276 : "token without window");
5277 }
5278
Vishnu Nairc519ff72021-01-21 08:23:08 -08005279 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005280 if (focusedToken != windowToken) {
5281 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5282 enabled ? "enable" : "disable");
5283 return;
5284 }
5285
5286 if (enabled == mFocusedWindowRequestedPointerCapture) {
5287 ALOGW("Ignoring request to %s Pointer Capture: "
5288 "window has %s requested pointer capture.",
5289 enabled ? "enable" : "disable", enabled ? "already" : "not");
5290 return;
5291 }
5292
5293 mFocusedWindowRequestedPointerCapture = enabled;
5294 setPointerCaptureLocked(enabled);
5295 } // release lock
5296
5297 // Wake the thread to process command entries.
5298 mLooper->wake();
5299}
5300
Michael Wright3dd60e22019-03-27 22:06:44 +00005301std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5302 const sp<IBinder>& token) {
5303 for (const auto& it : mGestureMonitorsByDisplay) {
5304 const std::vector<Monitor>& monitors = it.second;
5305 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005306 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005307 return it.first;
5308 }
5309 }
5310 }
5311 return std::nullopt;
5312}
5313
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005314std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5315 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5316 if (gesturePid.has_value()) {
5317 return gesturePid;
5318 }
5319 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5320}
5321
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005322sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005323 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005324 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005325 }
5326
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005327 for (const auto& [token, connection] : mConnectionsByToken) {
5328 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005329 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 }
5331 }
Robert Carr4e670e52018-08-15 13:26:12 -07005332
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005333 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334}
5335
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005336std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5337 sp<Connection> connection = getConnectionLocked(connectionToken);
5338 if (connection == nullptr) {
5339 return "<nullptr>";
5340 }
5341 return connection->getInputChannelName();
5342}
5343
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005344void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005345 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005346 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005347}
5348
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005349void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5350 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005351 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005352 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5353 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 commandEntry->connection = connection;
5355 commandEntry->eventTime = currentTime;
5356 commandEntry->seq = seq;
5357 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005358 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005359 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360}
5361
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005362void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5363 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005365 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005367 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5368 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005370 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371}
5372
Vishnu Nairad321cd2020-08-20 16:40:21 -07005373void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5374 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005375 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5376 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005377 commandEntry->oldToken = oldToken;
5378 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005379 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005380}
5381
arthurhungf452d0b2021-01-06 00:19:52 +08005382void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5383 std::unique_ptr<CommandEntry> commandEntry =
5384 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5385 commandEntry->newToken = token;
5386 commandEntry->x = x;
5387 commandEntry->y = y;
5388 postCommandLocked(std::move(commandEntry));
5389}
5390
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005391void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5392 if (connection == nullptr) {
5393 LOG_ALWAYS_FATAL("Caller must check for nullness");
5394 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005395 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5396 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005397 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005398 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005399 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005400 return;
5401 }
5402 /**
5403 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5404 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5405 * has changed. This could cause newer entries to time out before the already dispatched
5406 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5407 * processes the events linearly. So providing information about the oldest entry seems to be
5408 * most useful.
5409 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005410 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005411 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5412 std::string reason =
5413 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005414 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005415 ns2ms(currentWait),
5416 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005417 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005418 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005419
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005420 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5421
5422 // Stop waking up for events on this connection, it is already unresponsive
5423 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005424}
5425
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005426void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5427 std::string reason =
5428 StringPrintf("%s does not have a focused window", application->getName().c_str());
5429 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005430
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005431 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5432 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5433 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005434 postCommandLocked(std::move(commandEntry));
5435}
5436
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005437void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5438 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5439 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5440 commandEntry->obscuringPackage = obscuringPackage;
5441 postCommandLocked(std::move(commandEntry));
5442}
5443
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005444void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5445 const std::string& reason) {
5446 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5447 updateLastAnrStateLocked(windowLabel, reason);
5448}
5449
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005450void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5451 const std::string& reason) {
5452 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005453 updateLastAnrStateLocked(windowLabel, reason);
5454}
5455
5456void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5457 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005459 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 struct tm tm;
5461 localtime_r(&t, &tm);
5462 char timestr[64];
5463 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005464 mLastAnrState.clear();
5465 mLastAnrState += INDENT "ANR:\n";
5466 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005467 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5468 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005469 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470}
5471
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005472void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 mLock.unlock();
5474
5475 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5476
5477 mLock.lock();
5478}
5479
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005480void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 sp<Connection> connection = commandEntry->connection;
5482
5483 if (connection->status != Connection::STATUS_ZOMBIE) {
5484 mLock.unlock();
5485
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005486 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487
5488 mLock.lock();
5489 }
5490}
5491
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005492void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005493 sp<IBinder> oldToken = commandEntry->oldToken;
5494 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005495 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005496 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005497 mLock.lock();
5498}
5499
arthurhungf452d0b2021-01-06 00:19:52 +08005500void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5501 sp<IBinder> newToken = commandEntry->newToken;
5502 mLock.unlock();
5503 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5504 mLock.lock();
5505}
5506
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005507void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005509
5510 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5511
5512 mLock.lock();
5513}
5514
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005515void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005516 mLock.unlock();
5517
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005518 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519
5520 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005521}
5522
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005523void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005524 mLock.unlock();
5525
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005526 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5527
5528 mLock.lock();
5529}
5530
5531void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5532 mLock.unlock();
5533
5534 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5535
5536 mLock.lock();
5537}
5538
5539void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5540 mLock.unlock();
5541
5542 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005543
5544 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005545}
5546
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005547void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5548 mLock.unlock();
5549
5550 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5551
5552 mLock.lock();
5553}
5554
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5556 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005557 KeyEntry& entry = *(commandEntry->keyEntry);
5558 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559
5560 mLock.unlock();
5561
Michael Wright2b3c3302018-03-02 17:19:13 +00005562 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005563 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005564 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005565 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5566 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005567 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569
5570 mLock.lock();
5571
5572 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005573 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005575 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005577 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5578 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580}
5581
chaviwfd6d3512019-03-25 13:23:49 -07005582void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5583 mLock.unlock();
5584 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5585 mLock.lock();
5586}
5587
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005588/**
5589 * Connection is responsive if it has no events in the waitQueue that are older than the
5590 * current time.
5591 */
5592static bool isConnectionResponsive(const Connection& connection) {
5593 const nsecs_t currentTime = now();
5594 for (const DispatchEntry* entry : connection.waitQueue) {
5595 if (entry->timeoutTime < currentTime) {
5596 return false;
5597 }
5598 }
5599 return true;
5600}
5601
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005602void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005604 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005606 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
5608 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005609 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005610 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005611 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005613 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005614 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005615 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005616 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5617 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005618 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005619 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005620
5621 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005622 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005623 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005624 restartEvent =
5625 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005626 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005627 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005628 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5629 handled);
5630 } else {
5631 restartEvent = false;
5632 }
5633
5634 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005635 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005636 // contents of the wait queue to have been drained, so we need to double-check
5637 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005638 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5639 if (dispatchEntryIt != connection->waitQueue.end()) {
5640 dispatchEntry = *dispatchEntryIt;
5641 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005642 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5643 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005644 if (!connection->responsive) {
5645 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005646 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005647 // The connection was unresponsive, and now it's responsive.
5648 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005649 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005650 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005651 traceWaitQueueLength(connection);
5652 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005653 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005654 traceOutboundQueueLength(connection);
5655 } else {
5656 releaseDispatchEntry(dispatchEntry);
5657 }
5658 }
5659
5660 // Start the next dispatch cycle for this connection.
5661 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662}
5663
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005664void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5665 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5666 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5667 monitorUnresponsiveCommand->pid = pid;
5668 monitorUnresponsiveCommand->reason = std::move(reason);
5669 postCommandLocked(std::move(monitorUnresponsiveCommand));
5670}
5671
5672void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5673 std::string reason) {
5674 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5675 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5676 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5677 windowUnresponsiveCommand->reason = std::move(reason);
5678 postCommandLocked(std::move(windowUnresponsiveCommand));
5679}
5680
5681void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5682 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5683 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5684 monitorResponsiveCommand->pid = pid;
5685 postCommandLocked(std::move(monitorResponsiveCommand));
5686}
5687
5688void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5689 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5690 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5691 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5692 postCommandLocked(std::move(windowResponsiveCommand));
5693}
5694
5695/**
5696 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5697 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5698 * command entry to the command queue.
5699 */
5700void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5701 std::string reason) {
5702 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5703 if (connection.monitor) {
5704 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5705 reason.c_str());
5706 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5707 if (!pid.has_value()) {
5708 ALOGE("Could not find unresponsive monitor for connection %s",
5709 connection.inputChannel->getName().c_str());
5710 return;
5711 }
5712 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5713 return;
5714 }
5715 // If not a monitor, must be a window
5716 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5717 reason.c_str());
5718 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5719}
5720
5721/**
5722 * Tell the policy that a connection has become responsive so that it can stop ANR.
5723 */
5724void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5725 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5726 if (connection.monitor) {
5727 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5728 if (!pid.has_value()) {
5729 ALOGE("Could not find responsive monitor for connection %s",
5730 connection.inputChannel->getName().c_str());
5731 return;
5732 }
5733 sendMonitorResponsiveCommandLocked(pid.value());
5734 return;
5735 }
5736 // If not a monitor, must be a window
5737 sendWindowResponsiveCommandLocked(connectionToken);
5738}
5739
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005741 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005742 KeyEntry& keyEntry, bool handled) {
5743 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005744 if (!handled) {
5745 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005746 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005747 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005748 return false;
5749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005751 // Get the fallback key state.
5752 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005753 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005754 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005755 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005756 connection->inputState.removeFallbackKey(originalKeyCode);
5757 }
5758
5759 if (handled || !dispatchEntry->hasForegroundTarget()) {
5760 // If the application handles the original key for which we previously
5761 // generated a fallback or if the window is not a foreground window,
5762 // then cancel the associated fallback key, if any.
5763 if (fallbackKeyCode != -1) {
5764 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005766 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005767 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005768 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005770 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005771 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772
5773 mLock.unlock();
5774
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005775 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005776 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777
5778 mLock.lock();
5779
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005780 // Cancel the fallback key.
5781 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005783 "application handled the original non-fallback key "
5784 "or is no longer a foreground target, "
5785 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786 options.keyCode = fallbackKeyCode;
5787 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005789 connection->inputState.removeFallbackKey(originalKeyCode);
5790 }
5791 } else {
5792 // If the application did not handle a non-fallback key, first check
5793 // that we are in a good state to perform unhandled key event processing
5794 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005795 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005796 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005798 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005799 "since this is not an initial down. "
5800 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005801 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005803 return false;
5804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005806 // Dispatch the unhandled key to the policy.
5807#if DEBUG_OUTBOUND_EVENT_DETAILS
5808 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005809 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005810 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005811#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005812 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005813
5814 mLock.unlock();
5815
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005816 bool fallback =
5817 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005818 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005819
5820 mLock.lock();
5821
5822 if (connection->status != Connection::STATUS_NORMAL) {
5823 connection->inputState.removeFallbackKey(originalKeyCode);
5824 return false;
5825 }
5826
5827 // Latch the fallback keycode for this key on an initial down.
5828 // The fallback keycode cannot change at any other point in the lifecycle.
5829 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005831 fallbackKeyCode = event.getKeyCode();
5832 } else {
5833 fallbackKeyCode = AKEYCODE_UNKNOWN;
5834 }
5835 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5836 }
5837
5838 ALOG_ASSERT(fallbackKeyCode != -1);
5839
5840 // Cancel the fallback key if the policy decides not to send it anymore.
5841 // We will continue to dispatch the key to the policy but we will no
5842 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005843 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5844 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005845#if DEBUG_OUTBOUND_EVENT_DETAILS
5846 if (fallback) {
5847 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005848 "as a fallback for %d, but on the DOWN it had requested "
5849 "to send %d instead. Fallback canceled.",
5850 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005851 } else {
5852 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005853 "but on the DOWN it had requested to send %d. "
5854 "Fallback canceled.",
5855 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005856 }
5857#endif
5858
5859 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5860 "canceling fallback, policy no longer desires it");
5861 options.keyCode = fallbackKeyCode;
5862 synthesizeCancelationEventsForConnectionLocked(connection, options);
5863
5864 fallback = false;
5865 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005866 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005867 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005868 }
5869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870
5871#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005872 {
5873 std::string msg;
5874 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5875 connection->inputState.getFallbackKeys();
5876 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005877 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005878 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005879 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005880 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 }
5882#endif
5883
5884 if (fallback) {
5885 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005886 keyEntry.eventTime = event.getEventTime();
5887 keyEntry.deviceId = event.getDeviceId();
5888 keyEntry.source = event.getSource();
5889 keyEntry.displayId = event.getDisplayId();
5890 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5891 keyEntry.keyCode = fallbackKeyCode;
5892 keyEntry.scanCode = event.getScanCode();
5893 keyEntry.metaState = event.getMetaState();
5894 keyEntry.repeatCount = event.getRepeatCount();
5895 keyEntry.downTime = event.getDownTime();
5896 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897
5898#if DEBUG_OUTBOUND_EVENT_DETAILS
5899 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005900 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005901 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005902#endif
5903 return true; // restart the event
5904 } else {
5905#if DEBUG_OUTBOUND_EVENT_DETAILS
5906 ALOGD("Unhandled key event: No fallback key.");
5907#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005908
5909 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005910 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911 }
5912 }
5913 return false;
5914}
5915
5916bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005917 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 return false;
5920}
5921
5922void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5923 mLock.unlock();
5924
Sean Stoutb4e0a592021-02-23 07:34:53 -08005925 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
5926 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927
5928 mLock.lock();
5929}
5930
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005931void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5932 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 // TODO Write some statistics about how long we spend waiting.
5934}
5935
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005936/**
5937 * Report the touch event latency to the statsd server.
5938 * Input events are reported for statistics if:
5939 * - This is a touchscreen event
5940 * - InputFilter is not enabled
5941 * - Event is not injected or synthesized
5942 *
5943 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5944 * from getting aggregated with the "old" data.
5945 */
5946void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5947 REQUIRES(mLock) {
5948 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5949 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5950 if (!reportForStatistics) {
5951 return;
5952 }
5953
5954 if (mTouchStatistics.shouldReport()) {
5955 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5956 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5957 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5958 mTouchStatistics.reset();
5959 }
5960 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5961 mTouchStatistics.addValue(latencyMicros);
5962}
5963
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964void InputDispatcher::traceInboundQueueLengthLocked() {
5965 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005966 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 }
5968}
5969
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005970void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 if (ATRACE_ENABLED()) {
5972 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005973 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005974 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 }
5976}
5977
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005978void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 if (ATRACE_ENABLED()) {
5980 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005981 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005982 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 }
5984}
5985
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005986void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005989 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990 dumpDispatchStateLocked(dump);
5991
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005992 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005993 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005994 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 }
5996}
5997
5998void InputDispatcher::monitor() {
5999 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006000 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006001 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006002 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003}
6004
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006005/**
6006 * Wake up the dispatcher and wait until it processes all events and commands.
6007 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6008 * this method can be safely called from any thread, as long as you've ensured that
6009 * the work you are interested in completing has already been queued.
6010 */
6011bool InputDispatcher::waitForIdle() {
6012 /**
6013 * Timeout should represent the longest possible time that a device might spend processing
6014 * events and commands.
6015 */
6016 constexpr std::chrono::duration TIMEOUT = 100ms;
6017 std::unique_lock lock(mLock);
6018 mLooper->wake();
6019 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6020 return result == std::cv_status::no_timeout;
6021}
6022
Vishnu Naire798b472020-07-23 13:52:21 -07006023/**
6024 * Sets focus to the window identified by the token. This must be called
6025 * after updating any input window handles.
6026 *
6027 * Params:
6028 * request.token - input channel token used to identify the window that should gain focus.
6029 * request.focusedToken - the token that the caller expects currently to be focused. If the
6030 * specified token does not match the currently focused window, this request will be dropped.
6031 * If the specified focused token matches the currently focused window, the call will succeed.
6032 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6033 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6034 * when requesting the focus change. This determines which request gets
6035 * precedence if there is a focus change request from another source such as pointer down.
6036 */
Vishnu Nair958da932020-08-21 17:12:37 -07006037void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6038 { // acquire lock
6039 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006040 std::optional<FocusResolver::FocusChanges> changes =
6041 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6042 if (changes) {
6043 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006044 }
6045 } // release lock
6046 // Wake up poll loop since it may need to make new input dispatching choices.
6047 mLooper->wake();
6048}
6049
Vishnu Nairc519ff72021-01-21 08:23:08 -08006050void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6051 if (changes.oldFocus) {
6052 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006053 if (focusedInputChannel) {
6054 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6055 "focus left window");
6056 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006057 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006058 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006059 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006060 if (changes.newFocus) {
6061 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006062 }
6063
Prabir Pradhan99987712020-11-10 18:43:05 -08006064 // If a window has pointer capture, then it must have focus. We need to ensure that this
6065 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6066 // If the window loses focus before it loses pointer capture, then the window can be in a state
6067 // where it has pointer capture but not focus, violating the contract. Therefore we must
6068 // dispatch the pointer capture event before the focus event. Since focus events are added to
6069 // the front of the queue (above), we add the pointer capture event to the front of the queue
6070 // after the focus events are added. This ensures the pointer capture event ends up at the
6071 // front.
6072 disablePointerCaptureForcedLocked();
6073
Vishnu Nairc519ff72021-01-21 08:23:08 -08006074 if (mFocusedDisplayId == changes.displayId) {
6075 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006076 }
6077}
Vishnu Nair958da932020-08-21 17:12:37 -07006078
Prabir Pradhan99987712020-11-10 18:43:05 -08006079void InputDispatcher::disablePointerCaptureForcedLocked() {
6080 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6081 return;
6082 }
6083
6084 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6085
6086 if (mFocusedWindowRequestedPointerCapture) {
6087 mFocusedWindowRequestedPointerCapture = false;
6088 setPointerCaptureLocked(false);
6089 }
6090
6091 if (!mWindowTokenWithPointerCapture) {
6092 // No need to send capture changes because no window has capture.
6093 return;
6094 }
6095
6096 if (mPendingEvent != nullptr) {
6097 // Move the pending event to the front of the queue. This will give the chance
6098 // for the pending event to be dropped if it is a captured event.
6099 mInboundQueue.push_front(mPendingEvent);
6100 mPendingEvent = nullptr;
6101 }
6102
6103 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6104 false /* hasCapture */);
6105 mInboundQueue.push_front(std::move(entry));
6106}
6107
Prabir Pradhan99987712020-11-10 18:43:05 -08006108void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6109 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6110 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6111 commandEntry->enabled = enabled;
6112 postCommandLocked(std::move(commandEntry));
6113}
6114
6115void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6116 android::inputdispatcher::CommandEntry* commandEntry) {
6117 mLock.unlock();
6118
6119 mPolicy->setPointerCapture(commandEntry->enabled);
6120
6121 mLock.lock();
6122}
6123
Garfield Tane84e6f92019-08-29 17:28:41 -07006124} // namespace android::inputdispatcher