blob: 3183a98257ec7fdf3aae32245b3281e6dd432c23 [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 Vishniakou4c92c5f2021-03-05 02:32:57 +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
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700286/**
287 * Find the entry in std::unordered_map by value, and remove it.
288 * If more than one entry has the same value, then all matching
289 * key-value pairs will be removed.
290 *
291 * Return true if at least one value has been removed.
292 */
293template <typename K, typename V>
294static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
295 bool removed = false;
296 for (auto it = map.begin(); it != map.end();) {
297 if (it->second == value) {
298 it = map.erase(it);
299 removed = true;
300 } else {
301 it++;
302 }
303 }
304 return removed;
305}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306
chaviwaf87b3e2019-10-01 16:59:28 -0700307static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
308 if (first == second) {
309 return true;
310 }
311
312 if (first == nullptr || second == nullptr) {
313 return false;
314 }
315
316 return first->getToken() == second->getToken();
317}
318
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000319static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
320 if (first == nullptr || second == nullptr) {
321 return false;
322 }
323 return first->applicationInfo.token != nullptr &&
324 first->applicationInfo.token == second->applicationInfo.token;
325}
326
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800327static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
328 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
329}
330
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700332 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000333 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900334 if (eventEntry->type == EventEntry::Type::MOTION) {
335 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800336 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900337 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800338 // Use identity transform for events that are not pointer events because their axes
339 // values do not represent on-screen coordinates, so they should not have any window
340 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900341 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
342 1.0f /*globalScaleFactor*/);
343 }
344 }
345
chaviw1ff3d1e2020-07-01 15:53:47 -0700346 if (inputTarget.useDefaultPointerTransform()) {
347 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700348 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700349 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000350 }
351
352 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
353 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 std::vector<PointerCoords> pointerCoords;
356 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357
358 // Use the first pointer information to normalize all other pointers. This could be any pointer
359 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700360 // uses the transform for the normalized pointer.
361 const ui::Transform& firstPointerTransform =
362 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
363 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000364
365 // Iterate through all pointers in the event to normalize against the first.
366 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
367 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
368 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370
371 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 // First, apply the current pointer's transform to update the coordinates into
373 // window space.
374 pointerCoords[pointerIndex].transform(currTransform);
375 // Next, apply the inverse transform of the normalized coordinates so the
376 // current coordinates are transformed into the normalized coordinate space.
377 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378 }
379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700380 std::unique_ptr<MotionEntry> combinedMotionEntry =
381 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
382 motionEntry.deviceId, motionEntry.source,
383 motionEntry.displayId, motionEntry.policyFlags,
384 motionEntry.action, motionEntry.actionButton,
385 motionEntry.flags, motionEntry.metaState,
386 motionEntry.buttonState, motionEntry.classification,
387 motionEntry.edgeFlags, motionEntry.xPrecision,
388 motionEntry.yPrecision, motionEntry.xCursorPosition,
389 motionEntry.yCursorPosition, motionEntry.downTime,
390 motionEntry.pointerCount, motionEntry.pointerProperties,
391 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000392
393 if (motionEntry.injectionState) {
394 combinedMotionEntry->injectionState = motionEntry.injectionState;
395 combinedMotionEntry->injectionState->refCount += 1;
396 }
397
398 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700399 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
400 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000401 return dispatchEntry;
402}
403
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700404static void addGestureMonitors(const std::vector<Monitor>& monitors,
405 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
406 float yOffset = 0) {
407 if (monitors.empty()) {
408 return;
409 }
410 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
411 for (const Monitor& monitor : monitors) {
412 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
413 }
414}
415
Garfield Tan15601662020-09-22 15:32:38 -0700416static status_t openInputChannelPair(const std::string& name,
417 std::shared_ptr<InputChannel>& serverChannel,
418 std::unique_ptr<InputChannel>& clientChannel) {
419 std::unique_ptr<InputChannel> uniqueServerChannel;
420 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
421
422 serverChannel = std::move(uniqueServerChannel);
423 return result;
424}
425
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500426template <typename T>
427static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
428 if (lhs == nullptr && rhs == nullptr) {
429 return true;
430 }
431 if (lhs == nullptr || rhs == nullptr) {
432 return false;
433 }
434 return *lhs == *rhs;
435}
436
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000437static sp<IPlatformCompatNative> getCompatService() {
438 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
439 if (service == nullptr) {
440 ALOGE("Failed to link to compat service");
441 return nullptr;
442 }
443 return interface_cast<IPlatformCompatNative>(service);
444}
445
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000446static KeyEvent createKeyEvent(const KeyEntry& entry) {
447 KeyEvent event;
448 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
449 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
450 entry.repeatCount, entry.downTime, entry.eventTime);
451 return event;
452}
453
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000454static std::optional<int32_t> findMonitorPidByToken(
455 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
456 const sp<IBinder>& token) {
457 for (const auto& it : monitorsByDisplay) {
458 const std::vector<Monitor>& monitors = it.second;
459 for (const Monitor& monitor : monitors) {
460 if (monitor.inputChannel->getConnectionToken() == token) {
461 return monitor.pid;
462 }
463 }
464 }
465 return std::nullopt;
466}
467
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468// --- InputDispatcher ---
469
Garfield Tan00f511d2019-06-12 16:55:40 -0700470InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
471 : mPolicy(policy),
472 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700473 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800474 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700475 mAppSwitchSawKeyDown(false),
476 mAppSwitchDueTime(LONG_LONG_MAX),
477 mNextUnblockedEvent(nullptr),
478 mDispatchEnabled(false),
479 mDispatchFrozen(false),
480 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800481 // mInTouchMode will be initialized by the WindowManager to the default device config.
482 // To avoid leaking stack in case that call never comes, and for tests,
483 // initialize it here anyways.
484 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100485 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000486 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800487 mFocusedWindowRequestedPointerCapture(false),
488 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000489 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800491 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492
Yi Kong9b14ac62018-07-17 13:48:38 -0700493 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494
495 policy->getDispatcherConfiguration(&mConfig);
496}
497
498InputDispatcher::~InputDispatcher() {
499 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800500 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501
502 resetKeyRepeatLocked();
503 releasePendingEventLocked();
504 drainInboundQueueLocked();
505 }
506
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700507 while (!mConnectionsByFd.empty()) {
508 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700509 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 }
511}
512
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700513status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700514 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700515 return ALREADY_EXISTS;
516 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700517 mThread = std::make_unique<InputThread>(
518 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
519 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700520}
521
522status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700523 if (mThread && mThread->isCallingThread()) {
524 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700525 return INVALID_OPERATION;
526 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700527 mThread.reset();
528 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700529}
530
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531void InputDispatcher::dispatchOnce() {
532 nsecs_t nextWakeupTime = LONG_LONG_MAX;
533 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800534 std::scoped_lock _l(mLock);
535 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536
537 // Run a dispatch loop if there are no pending commands.
538 // The dispatch loop might enqueue commands to run afterwards.
539 if (!haveCommandsLocked()) {
540 dispatchOnceInnerLocked(&nextWakeupTime);
541 }
542
543 // Run all pending commands if there are any.
544 // If any commands were run then force the next poll to wake up immediately.
545 if (runCommandsLockedInterruptible()) {
546 nextWakeupTime = LONG_LONG_MIN;
547 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800548
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700549 // If we are still waiting for ack on some events,
550 // we might have to wake up earlier to check if an app is anr'ing.
551 const nsecs_t nextAnrCheck = processAnrsLocked();
552 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
553
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800554 // We are about to enter an infinitely long sleep, because we have no commands or
555 // pending or queued events
556 if (nextWakeupTime == LONG_LONG_MAX) {
557 mDispatcherEnteredIdle.notify_all();
558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 } // release lock
560
561 // Wait for callback or timeout or wake. (make sure we round up, not down)
562 nsecs_t currentTime = now();
563 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
564 mLooper->pollOnce(timeoutMillis);
565}
566
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700567/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500568 * Raise ANR if there is no focused window.
569 * Before the ANR is raised, do a final state check:
570 * 1. The currently focused application must be the same one we are waiting for.
571 * 2. Ensure we still don't have a focused window.
572 */
573void InputDispatcher::processNoFocusedWindowAnrLocked() {
574 // Check if the application that we are waiting for is still focused.
575 std::shared_ptr<InputApplicationHandle> focusedApplication =
576 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
577 if (focusedApplication == nullptr ||
578 focusedApplication->getApplicationToken() !=
579 mAwaitedFocusedApplication->getApplicationToken()) {
580 // Unexpected because we should have reset the ANR timer when focused application changed
581 ALOGE("Waited for a focused window, but focused application has already changed to %s",
582 focusedApplication->getName().c_str());
583 return; // The focused application has changed.
584 }
585
586 const sp<InputWindowHandle>& focusedWindowHandle =
587 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
588 if (focusedWindowHandle != nullptr) {
589 return; // We now have a focused window. No need for ANR.
590 }
591 onAnrLocked(mAwaitedFocusedApplication);
592}
593
594/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700595 * Check if any of the connections' wait queues have events that are too old.
596 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
597 * Return the time at which we should wake up next.
598 */
599nsecs_t InputDispatcher::processAnrsLocked() {
600 const nsecs_t currentTime = now();
601 nsecs_t nextAnrCheck = LONG_LONG_MAX;
602 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
603 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
604 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500605 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700606 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500607 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700608 return LONG_LONG_MIN;
609 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500610 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700611 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
612 }
613 }
614
615 // Check if any connection ANRs are due
616 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
617 if (currentTime < nextAnrCheck) { // most likely scenario
618 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
619 }
620
621 // If we reached here, we have an unresponsive connection.
622 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
623 if (connection == nullptr) {
624 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
625 return nextAnrCheck;
626 }
627 connection->responsive = false;
628 // Stop waking up for this unresponsive connection
629 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000630 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700631 return LONG_LONG_MIN;
632}
633
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500634std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700635 sp<InputWindowHandle> window = getWindowHandleLocked(token);
636 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500637 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500639 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700640}
641
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
643 nsecs_t currentTime = now();
644
Jeff Browndc5992e2014-04-11 01:27:26 -0700645 // Reset the key repeat timer whenever normal dispatch is suspended while the
646 // device is in a non-interactive state. This is to ensure that we abort a key
647 // repeat if the device is just coming out of sleep.
648 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 resetKeyRepeatLocked();
650 }
651
652 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
653 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100654 if (DEBUG_FOCUS) {
655 ALOGD("Dispatch frozen. Waiting some more.");
656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 return;
658 }
659
660 // Optimize latency of app switches.
661 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
662 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
663 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
664 if (mAppSwitchDueTime < *nextWakeupTime) {
665 *nextWakeupTime = mAppSwitchDueTime;
666 }
667
668 // Ready to start a new event.
669 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700670 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700671 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 if (isAppSwitchDue) {
673 // The inbound queue is empty so the app switch key we were waiting
674 // for will never arrive. Stop waiting for it.
675 resetPendingAppSwitchLocked(false);
676 isAppSwitchDue = false;
677 }
678
679 // Synthesize a key repeat if appropriate.
680 if (mKeyRepeatState.lastKeyEntry) {
681 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
682 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
683 } else {
684 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
685 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
686 }
687 }
688 }
689
690 // Nothing to do if there is no pending event.
691 if (!mPendingEvent) {
692 return;
693 }
694 } else {
695 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700696 mPendingEvent = mInboundQueue.front();
697 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 traceInboundQueueLengthLocked();
699 }
700
701 // Poke user activity for this event.
702 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700703 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 }
706
707 // Now we have an event to dispatch.
708 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700709 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700711 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700713 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700715 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717
718 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700719 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 }
721
722 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700723 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700724 const ConfigurationChangedEntry& typedEntry =
725 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700726 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700727 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700728 break;
729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700731 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700732 const DeviceResetEntry& typedEntry =
733 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700734 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700735 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700736 break;
737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100739 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700740 std::shared_ptr<FocusEntry> typedEntry =
741 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100742 dispatchFocusLocked(currentTime, typedEntry);
743 done = true;
744 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
745 break;
746 }
747
Prabir Pradhan99987712020-11-10 18:43:05 -0800748 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
749 const auto typedEntry =
750 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
751 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
752 done = true;
753 break;
754 }
755
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700756 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700757 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700759 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700760 resetPendingAppSwitchLocked(true);
761 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700762 } else if (dropReason == DropReason::NOT_DROPPED) {
763 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 }
765 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700766 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700769 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
770 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700772 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700773 break;
774 }
775
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700776 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700777 std::shared_ptr<MotionEntry> motionEntry =
778 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700779 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
780 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700782 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700784 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700785 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
786 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700788 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 }
Chris Yef59a2f42020-10-16 12:55:26 -0700791
792 case EventEntry::Type::SENSOR: {
793 std::shared_ptr<SensorEntry> sensorEntry =
794 std::static_pointer_cast<SensorEntry>(mPendingEvent);
795 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
796 dropReason = DropReason::APP_SWITCH;
797 }
798 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
799 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
800 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
801 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
802 dropReason = DropReason::STALE;
803 }
804 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
805 done = true;
806 break;
807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
809
810 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700812 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 }
Michael Wright3a981722015-06-10 15:26:13 +0100814 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815
816 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 }
819}
820
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700821/**
822 * Return true if the events preceding this incoming motion event should be dropped
823 * Return false otherwise (the default behaviour)
824 */
825bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700826 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700827 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700828
829 // Optimize case where the current application is unresponsive and the user
830 // decides to touch a window in a different application.
831 // If the application takes too long to catch up then we drop all events preceding
832 // the touch into the other window.
833 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700834 int32_t displayId = motionEntry.displayId;
835 int32_t x = static_cast<int32_t>(
836 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
837 int32_t y = static_cast<int32_t>(
838 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
839 sp<InputWindowHandle> touchedWindowHandle =
840 findTouchedWindowAtLocked(displayId, x, y, nullptr);
841 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700842 touchedWindowHandle->getApplicationToken() !=
843 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700844 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700845 ALOGI("Pruning input queue because user touched a different application while waiting "
846 "for %s",
847 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700848 return true;
849 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700850
851 // Alternatively, maybe there's a gesture monitor that could handle this event
852 std::vector<TouchedMonitor> gestureMonitors =
853 findTouchedGestureMonitorsLocked(displayId, {});
854 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
855 sp<Connection> connection =
856 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000857 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700858 // This monitor could take more input. Drop all events preceding this
859 // event, so that gesture monitor could get a chance to receive the stream
860 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
861 "responsive gesture monitor that may handle the event",
862 mAwaitedFocusedApplication->getName().c_str());
863 return true;
864 }
865 }
866 }
867
868 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
869 // yet been processed by some connections, the dispatcher will wait for these motion
870 // events to be processed before dispatching the key event. This is because these motion events
871 // may cause a new window to be launched, which the user might expect to receive focus.
872 // To prevent waiting forever for such events, just send the key to the currently focused window
873 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
874 ALOGD("Received a new pointer down event, stop waiting for events to process and "
875 "just send the pending key event to the focused window.");
876 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700877 }
878 return false;
879}
880
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700882 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700883 mInboundQueue.push_back(std::move(newEntry));
884 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 traceInboundQueueLengthLocked();
886
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700887 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700888 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 // Optimize app switch latency.
890 // If the application takes too long to catch up then we drop all events preceding
891 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700894 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700896 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700901 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 mAppSwitchSawKeyDown = false;
903 needWake = true;
904 }
905 }
906 }
907 break;
908 }
909
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700910 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700911 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
912 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700913 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100917 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700918 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
919 break;
920 }
921 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800922 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700923 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800924 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700925 // nothing to do
926 break;
927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
929
930 return needWake;
931}
932
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700933void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700934 // Do not store sensor event in recent queue to avoid flooding the queue.
935 if (entry->type != EventEntry::Type::SENSOR) {
936 mRecentQueue.push_back(entry);
937 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700938 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700939 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 }
941}
942
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700944 int32_t y, TouchState* touchState,
945 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700947 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
948 LOG_ALWAYS_FATAL(
949 "Must provide a valid touch state if adding portal windows or outside targets");
950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700952 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800953 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 const InputWindowInfo* windowInfo = windowHandle->getInfo();
955 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100956 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957
958 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100959 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
960 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
961 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800963 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 if (portalToDisplayId != ADISPLAY_ID_NONE &&
965 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800966 if (addPortalWindows) {
967 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700968 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800969 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700970 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700971 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 // Found window.
974 return windowHandle;
975 }
976 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800977
Michael Wright44753b12020-07-08 13:48:11 +0100978 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700979 touchState->addOrUpdateWindow(windowHandle,
980 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
981 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 }
985 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700986 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987}
988
Garfield Tane84e6f92019-08-29 17:28:41 -0700989std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700990 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000991 std::vector<TouchedMonitor> touchedMonitors;
992
993 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
994 addGestureMonitors(monitors, touchedMonitors);
995 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
996 const InputWindowInfo* windowInfo = portalWindow->getInfo();
997 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700998 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
999 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001000 }
1001 return touchedMonitors;
1002}
1003
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001004void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 const char* reason;
1006 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 reason = "inbound event was dropped because the policy consumed it";
1012 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001013 case DropReason::DISABLED:
1014 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 ALOGI("Dropped event because input dispatch is disabled.");
1016 }
1017 reason = "inbound event was dropped because input dispatch is disabled";
1018 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001019 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 ALOGI("Dropped event because of pending overdue app switch.");
1021 reason = "inbound event was dropped because of pending overdue app switch";
1022 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 ALOGI("Dropped event because the current application is not responding and the user "
1025 "has started interacting with a different application.");
1026 reason = "inbound event was dropped because the current application is not responding "
1027 "and the user has started interacting with a different application";
1028 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 ALOGI("Dropped event because it is stale.");
1031 reason = "inbound event was dropped because it is stale";
1032 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001033 case DropReason::NO_POINTER_CAPTURE:
1034 ALOGI("Dropped event because there is no window with Pointer Capture.");
1035 reason = "inbound event was dropped because there is no window with Pointer Capture";
1036 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001037 case DropReason::NOT_DROPPED: {
1038 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
1042
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001043 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001044 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1046 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001049 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001050 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1051 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1053 synthesizeCancelationEventsForAllConnectionsLocked(options);
1054 } else {
1055 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1056 synthesizeCancelationEventsForAllConnectionsLocked(options);
1057 }
1058 break;
1059 }
Chris Yef59a2f42020-10-16 12:55:26 -07001060 case EventEntry::Type::SENSOR: {
1061 break;
1062 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001063 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1064 break;
1065 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001066 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001067 case EventEntry::Type::CONFIGURATION_CHANGED:
1068 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001069 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001070 break;
1071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
1073}
1074
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001075static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1077 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078}
1079
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001080bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1081 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1082 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1083 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084}
1085
1086bool InputDispatcher::isAppSwitchPendingLocked() {
1087 return mAppSwitchDueTime != LONG_LONG_MAX;
1088}
1089
1090void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1091 mAppSwitchDueTime = LONG_LONG_MAX;
1092
1093#if DEBUG_APP_SWITCH
1094 if (handled) {
1095 ALOGD("App switch has arrived.");
1096 } else {
1097 ALOGD("App switch was abandoned.");
1098 }
1099#endif
1100}
1101
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001103 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104}
1105
1106bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001107 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 return false;
1109 }
1110
1111 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001112 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001113 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001115 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116
1117 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001118 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 return true;
1120}
1121
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001122void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1123 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124}
1125
1126void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001127 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001128 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001129 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 releaseInboundEventLocked(entry);
1131 }
1132 traceInboundQueueLengthLocked();
1133}
1134
1135void InputDispatcher::releasePendingEventLocked() {
1136 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001138 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
1140}
1141
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001142void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001144 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145#if DEBUG_DISPATCH_CYCLE
1146 ALOGD("Injected inbound event was dropped.");
1147#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001148 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001151 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 }
1153 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154}
1155
1156void InputDispatcher::resetKeyRepeatLocked() {
1157 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001158 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 }
1160}
1161
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1163 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164
Michael Wright2e732952014-09-24 13:26:59 -07001165 uint32_t policyFlags = entry->policyFlags &
1166 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001168 std::shared_ptr<KeyEntry> newEntry =
1169 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1170 entry->source, entry->displayId, policyFlags, entry->action,
1171 entry->flags, entry->keyCode, entry->scanCode,
1172 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 newEntry->syntheticRepeat = true;
1175 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001177 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178}
1179
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001181 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001183 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184#endif
1185
1186 // Reset key repeating in case a keyboard device was added or removed or something.
1187 resetKeyRepeatLocked();
1188
1189 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001190 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1191 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001192 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001193 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return true;
1195}
1196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1198 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1201 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202#endif
1203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001205 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 synthesizeCancelationEventsForAllConnectionsLocked(options);
1207 return true;
1208}
1209
Vishnu Nairad321cd2020-08-20 16:40:21 -07001210void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001211 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001212 if (mPendingEvent != nullptr) {
1213 // Move the pending event to the front of the queue. This will give the chance
1214 // for the pending event to get dispatched to the newly focused window
1215 mInboundQueue.push_front(mPendingEvent);
1216 mPendingEvent = nullptr;
1217 }
1218
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001219 std::unique_ptr<FocusEntry> focusEntry =
1220 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1221 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001222
1223 // This event should go to the front of the queue, but behind all other focus events
1224 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001226 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001227 [](const std::shared_ptr<EventEntry>& event) {
1228 return event->type == EventEntry::Type::FOCUS;
1229 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001230
1231 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001232 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001233}
1234
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001236 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001237 if (channel == nullptr) {
1238 return; // Window has gone away
1239 }
1240 InputTarget target;
1241 target.inputChannel = channel;
1242 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1243 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001244 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1245 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001246 std::string reason = std::string("reason=").append(entry->reason);
1247 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001248 dispatchEventLocked(currentTime, entry, {target});
1249}
1250
Prabir Pradhan99987712020-11-10 18:43:05 -08001251void InputDispatcher::dispatchPointerCaptureChangedLocked(
1252 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1253 DropReason& dropReason) {
1254 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001255 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1256 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1257 }
1258 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001259 // Pointer capture was already forcefully disabled because of focus change.
1260 dropReason = DropReason::NOT_DROPPED;
1261 return;
1262 }
1263
1264 // Set drop reason for early returns
1265 dropReason = DropReason::NO_POINTER_CAPTURE;
1266
1267 sp<IBinder> token;
1268 if (entry->pointerCaptureEnabled) {
1269 // Enable Pointer Capture
1270 if (!mFocusedWindowRequestedPointerCapture) {
1271 // This can happen if a window requests capture and immediately releases capture.
1272 ALOGW("No window requested Pointer Capture.");
1273 return;
1274 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001275 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001276 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1277 mWindowTokenWithPointerCapture = token;
1278 } else {
1279 // Disable Pointer Capture
1280 token = mWindowTokenWithPointerCapture;
1281 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001282 if (mFocusedWindowRequestedPointerCapture) {
1283 mFocusedWindowRequestedPointerCapture = false;
1284 setPointerCaptureLocked(false);
1285 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001286 }
1287
1288 auto channel = getInputChannelLocked(token);
1289 if (channel == nullptr) {
1290 // Window has gone away, clean up Pointer Capture state.
1291 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001292 if (mFocusedWindowRequestedPointerCapture) {
1293 mFocusedWindowRequestedPointerCapture = false;
1294 setPointerCaptureLocked(false);
1295 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001296 return;
1297 }
1298 InputTarget target;
1299 target.inputChannel = channel;
1300 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1301 entry->dispatchInProgress = true;
1302 dispatchEventLocked(currentTime, entry, {target});
1303
1304 dropReason = DropReason::NOT_DROPPED;
1305}
1306
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001310 if (!entry->dispatchInProgress) {
1311 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1312 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1313 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1314 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001315 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 // We have seen two identical key downs in a row which indicates that the device
1317 // driver is automatically generating key repeats itself. We take note of the
1318 // repeat here, but we disable our own next key repeat timer since it is clear that
1319 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001320 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1321 // Make sure we don't get key down from a different device. If a different
1322 // device Id has same key pressed down, the new device Id will replace the
1323 // current one to hold the key repeat with repeat count reset.
1324 // In the future when got a KEY_UP on the device id, drop it and do not
1325 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1327 resetKeyRepeatLocked();
1328 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1329 } else {
1330 // Not a repeat. Save key down state in case we do see a repeat later.
1331 resetKeyRepeatLocked();
1332 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1333 }
1334 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001335 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1336 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001337 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001338#if DEBUG_INBOUND_EVENT_DETAILS
1339 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1340#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001341 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 resetKeyRepeatLocked();
1343 }
1344
1345 if (entry->repeatCount == 1) {
1346 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1347 } else {
1348 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1349 }
1350
1351 entry->dispatchInProgress = true;
1352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001353 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 }
1355
1356 // Handle case where the policy asked us to try again later last time.
1357 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1358 if (currentTime < entry->interceptKeyWakeupTime) {
1359 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1360 *nextWakeupTime = entry->interceptKeyWakeupTime;
1361 }
1362 return false; // wait until next wakeup
1363 }
1364 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1365 entry->interceptKeyWakeupTime = 0;
1366 }
1367
1368 // Give the policy a chance to intercept the key.
1369 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1370 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001371 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001372 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001373 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001374 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001375 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001377 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 return false; // wait for the command to run
1379 } else {
1380 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1381 }
1382 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001383 if (*dropReason == DropReason::NOT_DROPPED) {
1384 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 }
1386 }
1387
1388 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001389 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001390 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001391 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1392 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001393 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return true;
1395 }
1396
1397 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001398 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001401 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 return false;
1403 }
1404
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001405 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001406 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 return true;
1408 }
1409
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001410 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001411 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412
1413 // Dispatch the key.
1414 dispatchEventLocked(currentTime, entry, inputTargets);
1415 return true;
1416}
1417
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001418void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001420 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001421 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1422 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001423 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1424 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1425 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426#endif
1427}
1428
Chris Yef59a2f42020-10-16 12:55:26 -07001429void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1430 mLock.unlock();
1431
1432 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1433 if (entry->accuracyChanged) {
1434 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1435 }
1436 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1437 entry->hwTimestamp, entry->values);
1438 mLock.lock();
1439}
1440
1441void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1442 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1443#if DEBUG_OUTBOUND_EVENT_DETAILS
1444 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1445 "source=0x%x, sensorType=%s",
1446 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001447 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001448#endif
1449 std::unique_ptr<CommandEntry> commandEntry =
1450 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1451 commandEntry->sensorEntry = entry;
1452 postCommandLocked(std::move(commandEntry));
1453}
1454
1455bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1456#if DEBUG_OUTBOUND_EVENT_DETAILS
1457 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1458 NamedEnum::string(sensorType).c_str());
1459#endif
1460 { // acquire lock
1461 std::scoped_lock _l(mLock);
1462
1463 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1464 std::shared_ptr<EventEntry> entry = *it;
1465 if (entry->type == EventEntry::Type::SENSOR) {
1466 it = mInboundQueue.erase(it);
1467 releaseInboundEventLocked(entry);
1468 }
1469 }
1470 }
1471 return true;
1472}
1473
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001474bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001475 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001476 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 entry->dispatchInProgress = true;
1480
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001481 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 }
1483
1484 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001485 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001486 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1488 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 return true;
1490 }
1491
1492 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1493
1494 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001495 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496
1497 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001498 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 if (isPointerEvent) {
1500 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001502 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001503 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 } else {
1505 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001506 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001507 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001509 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 return false;
1511 }
1512
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001514 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001515 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1516 return true;
1517 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001519 CancelationOptions::Mode mode(isPointerEvent
1520 ? CancelationOptions::CANCEL_POINTER_EVENTS
1521 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1522 CancelationOptions options(mode, "input event injection failed");
1523 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 return true;
1525 }
1526
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001527 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001528 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001530 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001531 std::unordered_map<int32_t, TouchState>::iterator it =
1532 mTouchStatesByDisplay.find(entry->displayId);
1533 if (it != mTouchStatesByDisplay.end()) {
1534 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001535 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001536 // The event has gone through these portal windows, so we add monitoring targets of
1537 // the corresponding displays as well.
1538 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001539 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001540 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001541 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001542 }
1543 }
1544 }
1545 }
1546
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 // Dispatch the motion.
1548 if (conflictingPointerActions) {
1549 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 synthesizeCancelationEventsForAllConnectionsLocked(options);
1552 }
1553 dispatchEventLocked(currentTime, entry, inputTargets);
1554 return true;
1555}
1556
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001557void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001559 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001560 ", policyFlags=0x%x, "
1561 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1562 "metaState=0x%x, buttonState=0x%x,"
1563 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001564 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1565 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1566 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001568 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001570 "x=%f, y=%f, pressure=%f, size=%f, "
1571 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1572 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001573 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1574 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1575 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1576 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1577 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1578 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1579 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1580 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1581 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1582 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 }
1584#endif
1585}
1586
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001587void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1588 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001589 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001590 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591#if DEBUG_DISPATCH_CYCLE
1592 ALOGD("dispatchEventToCurrentInputTargets");
1593#endif
1594
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001595 updateInteractionTokensLocked(*eventEntry, inputTargets);
1596
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1598
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001599 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001601 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001602 sp<Connection> connection =
1603 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001604 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001605 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001607 if (DEBUG_FOCUS) {
1608 ALOGD("Dropping event delivery to target with channel '%s' because it "
1609 "is no longer registered with the input dispatcher.",
1610 inputTarget.inputChannel->getName().c_str());
1611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 }
1613 }
1614}
1615
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001616void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1617 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1618 // If the policy decides to close the app, we will get a channel removal event via
1619 // unregisterInputChannel, and will clean up the connection that way. We are already not
1620 // sending new pointers to the connection when it blocked, but focused events will continue to
1621 // pile up.
1622 ALOGW("Canceling events for %s because it is unresponsive",
1623 connection->inputChannel->getName().c_str());
1624 if (connection->status == Connection::STATUS_NORMAL) {
1625 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1626 "application not responding");
1627 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 }
1629}
1630
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001631void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001632 if (DEBUG_FOCUS) {
1633 ALOGD("Resetting ANR timeouts.");
1634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635
1636 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001637 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001638 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639}
1640
Tiger Huang721e26f2018-07-24 22:26:19 +08001641/**
1642 * Get the display id that the given event should go to. If this event specifies a valid display id,
1643 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1644 * Focused display is the display that the user most recently interacted with.
1645 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001646int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001647 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001649 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1651 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 break;
1653 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001654 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001655 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1656 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 break;
1658 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001659 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001660 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001661 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001662 case EventEntry::Type::DEVICE_RESET:
1663 case EventEntry::Type::SENSOR: {
1664 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 return ADISPLAY_ID_NONE;
1666 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001667 }
1668 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1669}
1670
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001671bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1672 const char* focusedWindowName) {
1673 if (mAnrTracker.empty()) {
1674 // already processed all events that we waited for
1675 mKeyIsWaitingForEventsTimeout = std::nullopt;
1676 return false;
1677 }
1678
1679 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1680 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001681 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001682 mKeyIsWaitingForEventsTimeout = currentTime +
1683 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1684 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001685 return true;
1686 }
1687
1688 // We still have pending events, and already started the timer
1689 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1690 return true; // Still waiting
1691 }
1692
1693 // Waited too long, and some connection still hasn't processed all motions
1694 // Just send the key to the focused window
1695 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1696 focusedWindowName);
1697 mKeyIsWaitingForEventsTimeout = std::nullopt;
1698 return false;
1699}
1700
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001701InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1702 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1703 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001704 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705
Tiger Huang721e26f2018-07-24 22:26:19 +08001706 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001707 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001708 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001709 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1710
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 // If there is no currently focused window and no focused application
1712 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001713 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1714 ALOGI("Dropping %s event because there is no focused window or focused application in "
1715 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001716 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001717 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
1719
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001720 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1721 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1722 // start interacting with another application via touch (app switch). This code can be removed
1723 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1724 // an app is expected to have a focused window.
1725 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1726 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1727 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001728 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1729 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1730 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001731 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001732 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001733 ALOGW("Waiting because no window has focus but %s may eventually add a "
1734 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001735 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001736 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001737 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001738 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1739 // Already raised ANR. Drop the event
1740 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001741 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001742 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001743 } else {
1744 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001745 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001746 }
1747 }
1748
1749 // we have a valid, non-null focused window
1750 resetNoFocusedWindowTimeoutLocked();
1751
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001753 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001754 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 }
1756
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757 if (focusedWindowHandle->getInfo()->paused) {
1758 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001759 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001760 }
1761
1762 // If the event is a key event, then we must wait for all previous events to
1763 // complete before delivering it because previous events may have the
1764 // side-effect of transferring focus to a different window and we want to
1765 // ensure that the following keys are sent to the new window.
1766 //
1767 // Suppose the user touches a button in a window then immediately presses "A".
1768 // If the button causes a pop-up window to appear then we want to ensure that
1769 // the "A" key is delivered to the new pop-up window. This is because users
1770 // often anticipate pending UI changes when typing on a keyboard.
1771 // To obtain this behavior, we must serialize key events with respect to all
1772 // prior input events.
1773 if (entry.type == EventEntry::Type::KEY) {
1774 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1775 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001776 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 }
1779
1780 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001781 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1783 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784
1785 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787}
1788
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001789/**
1790 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1791 * that are currently unresponsive.
1792 */
1793std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1794 const std::vector<TouchedMonitor>& monitors) const {
1795 std::vector<TouchedMonitor> responsiveMonitors;
1796 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1797 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1798 sp<Connection> connection = getConnectionLocked(
1799 monitor.monitor.inputChannel->getConnectionToken());
1800 if (connection == nullptr) {
1801 ALOGE("Could not find connection for monitor %s",
1802 monitor.monitor.inputChannel->getName().c_str());
1803 return false;
1804 }
1805 if (!connection->responsive) {
1806 ALOGW("Unresponsive monitor %s will not get the new gesture",
1807 connection->inputChannel->getName().c_str());
1808 return false;
1809 }
1810 return true;
1811 });
1812 return responsiveMonitors;
1813}
1814
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1816 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1817 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001818 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 enum InjectionPermission {
1820 INJECTION_PERMISSION_UNKNOWN,
1821 INJECTION_PERMISSION_GRANTED,
1822 INJECTION_PERMISSION_DENIED
1823 };
1824
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 // For security reasons, we defer updating the touch state until we are sure that
1826 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827 int32_t displayId = entry.displayId;
1828 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1830
1831 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001834 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1835 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001837 // Copy current touch state into tempTouchState.
1838 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1839 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001840 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001841 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001842 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1843 mTouchStatesByDisplay.find(displayId);
1844 if (oldStateIt != mTouchStatesByDisplay.end()) {
1845 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001846 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001847 }
1848
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001849 bool isSplit = tempTouchState.split;
1850 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1851 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1852 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001853 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1854 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1855 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1856 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1857 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001858 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 bool wrongDevice = false;
1860 if (newGesture) {
1861 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001862 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001863 ALOGI("Dropping event because a pointer for a different device is already down "
1864 "in display %" PRId32,
1865 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001866 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001867 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 switchedDevice = false;
1869 wrongDevice = true;
1870 goto Failed;
1871 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001872 tempTouchState.reset();
1873 tempTouchState.down = down;
1874 tempTouchState.deviceId = entry.deviceId;
1875 tempTouchState.source = entry.source;
1876 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001878 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001879 ALOGI("Dropping move event because a pointer for a different device is already active "
1880 "in display %" PRId32,
1881 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001882 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001883 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001884 switchedDevice = false;
1885 wrongDevice = true;
1886 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 }
1888
1889 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1890 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1891
Garfield Tan00f511d2019-06-12 16:55:40 -07001892 int32_t x;
1893 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001895 // Always dispatch mouse events to cursor position.
1896 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001897 x = int32_t(entry.xCursorPosition);
1898 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001899 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001900 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1901 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001902 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001903 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001904 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001905 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1906 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001907
1908 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001909 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001910 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001913 if (newTouchedWindowHandle != nullptr &&
1914 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001915 // New window supports splitting, but we should never split mouse events.
1916 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 } else if (isSplit) {
1918 // New window does not support splitting but we have already split events.
1919 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001920 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 }
1922
1923 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001924 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001926 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001927 }
1928
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1930 ALOGI("Not sending touch event to %s because it is paused",
1931 newTouchedWindowHandle->getName().c_str());
1932 newTouchedWindowHandle = nullptr;
1933 }
1934
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001935 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001937 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1938 if (!isResponsive) {
1939 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001940 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1941 newTouchedWindowHandle = nullptr;
1942 }
1943 }
1944
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001945 // Drop events that can't be trusted due to occlusion
1946 if (newTouchedWindowHandle != nullptr &&
1947 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1948 TouchOcclusionInfo occlusionInfo =
1949 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001950 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001951 if (DEBUG_TOUCH_OCCLUSION) {
1952 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1953 for (const auto& log : occlusionInfo.debugInfo) {
1954 ALOGD("%s", log.c_str());
1955 }
1956 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001957 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1958 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1959 ALOGW("Dropping untrusted touch event due to %s/%d",
1960 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1961 newTouchedWindowHandle = nullptr;
1962 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001963 }
1964 }
1965
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001966 // Also don't send the new touch event to unresponsive gesture monitors
1967 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1968
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1970 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001971 "(%d, %d) in display %" PRId32 ".",
1972 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001973 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001974 goto Failed;
1975 }
1976
1977 if (newTouchedWindowHandle != nullptr) {
1978 // Set target flags.
1979 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1980 if (isSplit) {
1981 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001983 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1984 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1985 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1986 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1987 }
1988
1989 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001990 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1991 newHoverWindowHandle = nullptr;
1992 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001993 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001994 }
1995
1996 // Update the temporary touch state.
1997 BitSet32 pointerIds;
1998 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001999 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 pointerIds.markBit(pointerId);
2001 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002002 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 }
2004
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002005 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 } else {
2007 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2008
2009 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002010 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002011 if (DEBUG_FOCUS) {
2012 ALOGD("Dropping event because the pointer is not down or we previously "
2013 "dropped the pointer down event in display %" PRId32,
2014 displayId);
2015 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002016 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 goto Failed;
2018 }
2019
2020 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002022 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2024 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025
2026 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002027 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002028 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002029 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2030 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002031 if (DEBUG_FOCUS) {
2032 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2033 oldTouchedWindowHandle->getName().c_str(),
2034 newTouchedWindowHandle->getName().c_str(), displayId);
2035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002037 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2038 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2039 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040
2041 // Make a slippery entrance into the new window.
2042 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2043 isSplit = true;
2044 }
2045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046 int32_t targetFlags =
2047 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 if (isSplit) {
2049 targetFlags |= InputTarget::FLAG_SPLIT;
2050 }
2051 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2052 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002053 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2054 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
2056
2057 BitSet32 pointerIds;
2058 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002059 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002061 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
2063 }
2064 }
2065
2066 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002067 // Let the previous window know that the hover sequence is over, unless we already did it
2068 // when dispatching it as is to newTouchedWindowHandle.
2069 if (mLastHoverWindowHandle != nullptr &&
2070 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2071 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072#if DEBUG_HOVER
2073 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002076 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2077 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 }
2079
Garfield Tandf26e862020-07-01 20:18:19 -07002080 // Let the new window know that the hover sequence is starting, unless we already did it
2081 // when dispatching it as is to newTouchedWindowHandle.
2082 if (newHoverWindowHandle != nullptr &&
2083 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2084 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085#if DEBUG_HOVER
2086 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002087 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002089 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2090 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2091 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
2093 }
2094
2095 // Check permission to inject into all touched foreground windows and ensure there
2096 // is at least one touched foreground window.
2097 {
2098 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002099 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2101 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002102 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002103 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 injectionPermission = INJECTION_PERMISSION_DENIED;
2105 goto Failed;
2106 }
2107 }
2108 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002109 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002110 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002111 ALOGI("Dropping event because there is no touched foreground window in display "
2112 "%" PRId32 " or gesture monitor to receive it.",
2113 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002114 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 goto Failed;
2116 }
2117
2118 // Permission granted to injection into all touched foreground windows.
2119 injectionPermission = INJECTION_PERMISSION_GRANTED;
2120 }
2121
2122 // Check whether windows listening for outside touches are owned by the same UID. If it is
2123 // set the policy flag that we will not reveal coordinate information to this window.
2124 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2125 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002126 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002127 if (foregroundWindowHandle) {
2128 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002129 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002130 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2131 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2132 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002133 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2134 InputTarget::FLAG_ZERO_COORDS,
2135 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138 }
2139 }
2140 }
2141
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 // If this is the first pointer going down and the touched window has a wallpaper
2143 // then also add the touched wallpaper windows so they are locked in for the duration
2144 // of the touch gesture.
2145 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2146 // engine only supports touch events. We would need to add a mechanism similar
2147 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2148 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2149 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002150 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002151 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002152 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002153 getWindowHandlesLocked(displayId);
2154 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002156 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002157 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002158 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002159 .addOrUpdateWindow(windowHandle,
2160 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2161 InputTarget::
2162 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2163 InputTarget::FLAG_DISPATCH_AS_IS,
2164 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166 }
2167 }
2168 }
2169
2170 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002171 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002175 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
2177
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002181 }
2182
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 // Drop the outside or hover touch windows since we will not care about them
2184 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002185 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186
2187Failed:
2188 // Check injection permission once and for all.
2189 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002190 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 injectionPermission = INJECTION_PERMISSION_GRANTED;
2192 } else {
2193 injectionPermission = INJECTION_PERMISSION_DENIED;
2194 }
2195 }
2196
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002197 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2198 return injectionResult;
2199 }
2200
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002202 if (!wrongDevice) {
2203 if (switchedDevice) {
2204 if (DEBUG_FOCUS) {
2205 ALOGD("Conflicting pointer actions: Switched to a different device.");
2206 }
2207 *outConflictingPointerActions = true;
2208 }
2209
2210 if (isHoverAction) {
2211 // Started hovering, therefore no longer down.
2212 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002213 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002214 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2215 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 *outConflictingPointerActions = true;
2218 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002219 tempTouchState.reset();
2220 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2221 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2222 tempTouchState.deviceId = entry.deviceId;
2223 tempTouchState.source = entry.source;
2224 tempTouchState.displayId = displayId;
2225 }
2226 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2227 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2228 // All pointers up or canceled.
2229 tempTouchState.reset();
2230 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2231 // First pointer went down.
2232 if (oldState && oldState->down) {
2233 if (DEBUG_FOCUS) {
2234 ALOGD("Conflicting pointer actions: Down received while already down.");
2235 }
2236 *outConflictingPointerActions = true;
2237 }
2238 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2239 // One pointer went up.
2240 if (isSplit) {
2241 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2242 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002244 for (size_t i = 0; i < tempTouchState.windows.size();) {
2245 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2246 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2247 touchedWindow.pointerIds.clearBit(pointerId);
2248 if (touchedWindow.pointerIds.isEmpty()) {
2249 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2250 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002253 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002255 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002256 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002257
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002258 // Save changes unless the action was scroll in which case the temporary touch
2259 // state was only valid for this one action.
2260 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2261 if (tempTouchState.displayId >= 0) {
2262 mTouchStatesByDisplay[displayId] = tempTouchState;
2263 } else {
2264 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002268 // Update hover state.
2269 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 return injectionResult;
2273}
2274
2275void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002276 int32_t targetFlags, BitSet32 pointerIds,
2277 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002278 std::vector<InputTarget>::iterator it =
2279 std::find_if(inputTargets.begin(), inputTargets.end(),
2280 [&windowHandle](const InputTarget& inputTarget) {
2281 return inputTarget.inputChannel->getConnectionToken() ==
2282 windowHandle->getToken();
2283 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002284
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002285 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002286
2287 if (it == inputTargets.end()) {
2288 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002289 std::shared_ptr<InputChannel> inputChannel =
2290 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002291 if (inputChannel == nullptr) {
2292 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2293 return;
2294 }
2295 inputTarget.inputChannel = inputChannel;
2296 inputTarget.flags = targetFlags;
2297 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2298 inputTargets.push_back(inputTarget);
2299 it = inputTargets.end() - 1;
2300 }
2301
2302 ALOG_ASSERT(it->flags == targetFlags);
2303 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2304
chaviw1ff3d1e2020-07-01 15:53:47 -07002305 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306}
2307
Michael Wright3dd60e22019-03-27 22:06:44 +00002308void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309 int32_t displayId, float xOffset,
2310 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002311 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2312 mGlobalMonitorsByDisplay.find(displayId);
2313
2314 if (it != mGlobalMonitorsByDisplay.end()) {
2315 const std::vector<Monitor>& monitors = it->second;
2316 for (const Monitor& monitor : monitors) {
2317 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 }
2320}
2321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002322void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2323 float yOffset,
2324 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002325 InputTarget target;
2326 target.inputChannel = monitor.inputChannel;
2327 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002328 ui::Transform t;
2329 t.set(xOffset, yOffset);
2330 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002331 inputTargets.push_back(target);
2332}
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002335 const InjectionState* injectionState) {
2336 if (injectionState &&
2337 (windowHandle == nullptr ||
2338 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2339 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002340 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 "owned by uid %d",
2343 injectionState->injectorPid, injectionState->injectorUid,
2344 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 } else {
2346 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002347 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
2349 return false;
2350 }
2351 return true;
2352}
2353
Robert Carrc9bf1d32020-04-13 17:21:08 -07002354/**
2355 * Indicate whether one window handle should be considered as obscuring
2356 * another window handle. We only check a few preconditions. Actually
2357 * checking the bounds is left to the caller.
2358 */
2359static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2360 const sp<InputWindowHandle>& otherHandle) {
2361 // Compare by token so cloned layers aren't counted
2362 if (haveSameToken(windowHandle, otherHandle)) {
2363 return false;
2364 }
2365 auto info = windowHandle->getInfo();
2366 auto otherInfo = otherHandle->getInfo();
2367 if (!otherInfo->visible) {
2368 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002369 } else if (otherInfo->alpha == 0 &&
2370 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2371 // Those act as if they were invisible, so we don't need to flag them.
2372 // We do want to potentially flag touchable windows even if they have 0
2373 // opacity, since they can consume touches and alter the effects of the
2374 // user interaction (eg. apps that rely on
2375 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2376 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2377 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002378 } else if (info->ownerUid == otherInfo->ownerUid) {
2379 // If ownerUid is the same we don't generate occlusion events as there
2380 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002381 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002382 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002383 return false;
2384 } else if (otherInfo->displayId != info->displayId) {
2385 return false;
2386 }
2387 return true;
2388}
2389
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002390/**
2391 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2392 * untrusted, one should check:
2393 *
2394 * 1. If result.hasBlockingOcclusion is true.
2395 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2396 * BLOCK_UNTRUSTED.
2397 *
2398 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2399 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2400 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2401 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2402 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2403 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2404 *
2405 * If neither of those is true, then it means the touch can be allowed.
2406 */
2407InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2408 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002409 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2410 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002411 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2412 TouchOcclusionInfo info;
2413 info.hasBlockingOcclusion = false;
2414 info.obscuringOpacity = 0;
2415 info.obscuringUid = -1;
2416 std::map<int32_t, float> opacityByUid;
2417 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2418 if (windowHandle == otherHandle) {
2419 break; // All future windows are below us. Exit early.
2420 }
2421 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002422 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2423 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002424 if (DEBUG_TOUCH_OCCLUSION) {
2425 info.debugInfo.push_back(
2426 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2427 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002428 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2429 // we perform the checks below to see if the touch can be propagated or not based on the
2430 // window's touch occlusion mode
2431 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2432 info.hasBlockingOcclusion = true;
2433 info.obscuringUid = otherInfo->ownerUid;
2434 info.obscuringPackage = otherInfo->packageName;
2435 break;
2436 }
2437 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2438 uint32_t uid = otherInfo->ownerUid;
2439 float opacity =
2440 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2441 // Given windows A and B:
2442 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2443 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2444 opacityByUid[uid] = opacity;
2445 if (opacity > info.obscuringOpacity) {
2446 info.obscuringOpacity = opacity;
2447 info.obscuringUid = uid;
2448 info.obscuringPackage = otherInfo->packageName;
2449 }
2450 }
2451 }
2452 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002453 if (DEBUG_TOUCH_OCCLUSION) {
2454 info.debugInfo.push_back(
2455 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2456 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002457 return info;
2458}
2459
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002460std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2461 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002462 return StringPrintf(INDENT2
2463 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2464 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2465 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2466 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002467 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002468 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002469 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002470 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2471 info->frameTop, info->frameRight, info->frameBottom,
2472 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002473 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2474 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2475 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002476}
2477
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002478bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2479 if (occlusionInfo.hasBlockingOcclusion) {
2480 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2481 occlusionInfo.obscuringUid);
2482 return false;
2483 }
2484 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2485 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2486 "%.2f, maximum allowed = %.2f)",
2487 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2488 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2489 return false;
2490 }
2491 return true;
2492}
2493
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002494bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2495 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002497 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002498 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002499 if (windowHandle == otherHandle) {
2500 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002503 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002504 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 return true;
2506 }
2507 }
2508 return false;
2509}
2510
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002511bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2512 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002513 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002514 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002515 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002516 if (windowHandle == otherHandle) {
2517 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002518 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002519 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002520 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002521 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002522 return true;
2523 }
2524 }
2525 return false;
2526}
2527
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002528std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002529 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002531 if (applicationHandle != nullptr) {
2532 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002533 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 } else {
2535 return applicationHandle->getName();
2536 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002537 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002538 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002540 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
2542}
2543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002544void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002545 if (eventEntry.type == EventEntry::Type::FOCUS ||
2546 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2547 // Focus or pointer capture changed events are passed to apps, but do not represent user
2548 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002549 return;
2550 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002551 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002552 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002553 if (focusedWindowHandle != nullptr) {
2554 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002555 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002557 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558#endif
2559 return;
2560 }
2561 }
2562
2563 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002564 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002565 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002566 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2567 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002568 return;
2569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002571 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002572 eventType = USER_ACTIVITY_EVENT_TOUCH;
2573 }
2574 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002576 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002577 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2578 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 return;
2580 }
2581 eventType = USER_ACTIVITY_EVENT_BUTTON;
2582 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002584 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002585 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002586 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002587 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002588 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002589 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002590 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002591 break;
2592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
2594
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002595 std::unique_ptr<CommandEntry> commandEntry =
2596 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002597 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002599 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002600 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601}
2602
2603void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002604 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002605 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002606 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002607 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002609 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002610 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002611 ATRACE_NAME(message.c_str());
2612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613#if DEBUG_DISPATCH_CYCLE
2614 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002615 "globalScaleFactor=%f, pointerIds=0x%x %s",
2616 connection->getInputChannelName().c_str(), inputTarget.flags,
2617 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2618 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619#endif
2620
2621 // Skip this event if the connection status is not normal.
2622 // We don't want to enqueue additional outbound events if the connection is broken.
2623 if (connection->status != Connection::STATUS_NORMAL) {
2624#if DEBUG_DISPATCH_CYCLE
2625 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002626 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627#endif
2628 return;
2629 }
2630
2631 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002632 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2633 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2634 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002635 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002637 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002638 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002639 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002640 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 if (!splitMotionEntry) {
2642 return; // split event was dropped
2643 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002644 if (DEBUG_FOCUS) {
2645 ALOGD("channel '%s' ~ Split motion event.",
2646 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002647 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002648 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002649 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2650 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 return;
2652 }
2653 }
2654
2655 // Not splitting. Enqueue dispatch entries for the event as is.
2656 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2657}
2658
2659void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002661 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002662 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002663 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002664 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002665 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002666 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002667 ATRACE_NAME(message.c_str());
2668 }
2669
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002670 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671
2672 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002673 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002674 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002675 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002676 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002677 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002678 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002679 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002680 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002681 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002683 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002684 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
2686 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002687 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 startDispatchCycleLocked(currentTime, connection);
2689 }
2690}
2691
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002693 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002694 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002695 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002696 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002697 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2698 connection->getInputChannelName().c_str(),
2699 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002700 ATRACE_NAME(message.c_str());
2701 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002702 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 if (!(inputTargetFlags & dispatchMode)) {
2704 return;
2705 }
2706 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2707
2708 // This is a new event.
2709 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002710 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002711 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002713 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2714 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002715 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002717 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002718 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002719 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002720 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002721 dispatchEntry->resolvedAction = keyEntry.action;
2722 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2725 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2728 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 return; // skip the inconsistent event
2731 }
2732 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002735 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002736 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002737 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2738 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2739 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2740 static_cast<int32_t>(IdGenerator::Source::OTHER);
2741 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2743 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2744 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2745 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2746 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2747 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2748 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2749 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2750 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2751 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2752 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002753 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002754 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002755 }
2756 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002757 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2758 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2761 "event",
2762 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002767 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002768 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2769 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2770 }
2771 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2772 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002775 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2776 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2779 "event",
2780 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002782 return; // skip the inconsistent event
2783 }
2784
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002785 dispatchEntry->resolvedEventId =
2786 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2787 ? mIdGenerator.nextId()
2788 : motionEntry.id;
2789 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2790 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2791 ") to MotionEvent(id=0x%" PRIx32 ").",
2792 motionEntry.id, dispatchEntry->resolvedEventId);
2793 ATRACE_NAME(message.c_str());
2794 }
2795
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002796 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002797 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002798
2799 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002801 case EventEntry::Type::FOCUS:
2802 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002803 break;
2804 }
Chris Yef59a2f42020-10-16 12:55:26 -07002805 case EventEntry::Type::SENSOR: {
2806 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2807 break;
2808 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002809 case EventEntry::Type::CONFIGURATION_CHANGED:
2810 case EventEntry::Type::DEVICE_RESET: {
2811 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002812 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002813 break;
2814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 }
2816
2817 // Remember that we are waiting for this dispatch to complete.
2818 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002819 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821
2822 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002823 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002824 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002825}
2826
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002827/**
2828 * This function is purely for debugging. It helps us understand where the user interaction
2829 * was taking place. For example, if user is touching launcher, we will see a log that user
2830 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2831 * We will see both launcher and wallpaper in that list.
2832 * Once the interaction with a particular set of connections starts, no new logs will be printed
2833 * until the set of interacted connections changes.
2834 *
2835 * The following items are skipped, to reduce the logspam:
2836 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2837 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2838 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2839 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2840 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002841 */
2842void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2843 const std::vector<InputTarget>& targets) {
2844 // Skip ACTION_UP events, and all events other than keys and motions
2845 if (entry.type == EventEntry::Type::KEY) {
2846 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2847 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2848 return;
2849 }
2850 } else if (entry.type == EventEntry::Type::MOTION) {
2851 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2852 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2853 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2854 return;
2855 }
2856 } else {
2857 return; // Not a key or a motion
2858 }
2859
2860 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2861 std::vector<sp<Connection>> newConnections;
2862 for (const InputTarget& target : targets) {
2863 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2864 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2865 continue; // Skip windows that receive ACTION_OUTSIDE
2866 }
2867
2868 sp<IBinder> token = target.inputChannel->getConnectionToken();
2869 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002870 if (connection == nullptr) {
2871 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002872 }
2873 newConnectionTokens.insert(std::move(token));
2874 newConnections.emplace_back(connection);
2875 }
2876 if (newConnectionTokens == mInteractionConnectionTokens) {
2877 return; // no change
2878 }
2879 mInteractionConnectionTokens = newConnectionTokens;
2880
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002881 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002882 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002883 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002884 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002885 std::string message = "Interaction with: " + targetList;
2886 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002887 message += "<none>";
2888 }
2889 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2890}
2891
chaviwfd6d3512019-03-25 13:23:49 -07002892void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002893 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002894 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002895 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2896 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002897 return;
2898 }
2899
Vishnu Nairc519ff72021-01-21 08:23:08 -08002900 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002901 if (focusedToken == token) {
2902 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002903 return;
2904 }
2905
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002906 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2907 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002908 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002909 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910}
2911
2912void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002914 if (ATRACE_ENABLED()) {
2915 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002917 ATRACE_NAME(message.c_str());
2918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921#endif
2922
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002923 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2924 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002926 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002927 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002928 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
2930 // Publish the event.
2931 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002932 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2933 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002934 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002935 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2936 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002938 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002939 status = connection->inputPublisher
2940 .publishKeyEvent(dispatchEntry->seq,
2941 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2942 keyEntry.source, keyEntry.displayId,
2943 std::move(hmac), dispatchEntry->resolvedAction,
2944 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2945 keyEntry.scanCode, keyEntry.metaState,
2946 keyEntry.repeatCount, keyEntry.downTime,
2947 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 }
2950
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002951 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002955 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002956
chaviw82357092020-01-28 13:13:06 -08002957 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002958 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2960 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002961 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002962 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2963 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002964 // Don't apply window scale here since we don't want scale to affect raw
2965 // coordinates. The scale will be sent back to the client and applied
2966 // later when requesting relative coordinates.
2967 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2968 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969 }
2970 usingCoords = scaledCoords;
2971 }
2972 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 // We don't want the dispatch target to know.
2974 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002975 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 scaledCoords[i].clear();
2977 }
2978 usingCoords = scaledCoords;
2979 }
2980 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002982 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983
2984 // Publish the motion event.
2985 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002986 .publishMotionEvent(dispatchEntry->seq,
2987 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 motionEntry.deviceId, motionEntry.source,
2989 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002990 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002991 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002992 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002993 motionEntry.edgeFlags, motionEntry.metaState,
2994 motionEntry.buttonState,
2995 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002996 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002997 motionEntry.xPrecision, motionEntry.yPrecision,
2998 motionEntry.xCursorPosition,
2999 motionEntry.yCursorPosition,
3000 motionEntry.downTime, motionEntry.eventTime,
3001 motionEntry.pointerCount,
3002 motionEntry.pointerProperties, usingCoords);
3003 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 break;
3005 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003006
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003007 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003008 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003009 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003010 focusEntry.id,
3011 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003012 mInTouchMode);
3013 break;
3014 }
3015
Prabir Pradhan99987712020-11-10 18:43:05 -08003016 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3017 const auto& captureEntry =
3018 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3019 status = connection->inputPublisher
3020 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3021 captureEntry.pointerCaptureEnabled);
3022 break;
3023 }
3024
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003025 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003026 case EventEntry::Type::DEVICE_RESET:
3027 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003028 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003029 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 }
3033
3034 // Check the result.
3035 if (status) {
3036 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003037 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003039 "This is unexpected because the wait queue is empty, so the pipe "
3040 "should be empty and we shouldn't have any problems writing an "
3041 "event to it, status=%d",
3042 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3044 } else {
3045 // Pipe is full and we are waiting for the app to finish process some events
3046 // before sending more events to it.
3047#if DEBUG_DISPATCH_CYCLE
3048 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003049 "waiting for the application to catch up",
3050 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
3053 } else {
3054 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 "status=%d",
3056 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3058 }
3059 return;
3060 }
3061
3062 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003063 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3064 connection->outboundQueue.end(),
3065 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003066 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003067 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003068 if (connection->responsive) {
3069 mAnrTracker.insert(dispatchEntry->timeoutTime,
3070 connection->inputChannel->getConnectionToken());
3071 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003072 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 }
3074}
3075
chaviw09c8d2d2020-08-24 15:48:26 -07003076std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3077 size_t size;
3078 switch (event.type) {
3079 case VerifiedInputEvent::Type::KEY: {
3080 size = sizeof(VerifiedKeyEvent);
3081 break;
3082 }
3083 case VerifiedInputEvent::Type::MOTION: {
3084 size = sizeof(VerifiedMotionEvent);
3085 break;
3086 }
3087 }
3088 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3089 return mHmacKeyManager.sign(start, size);
3090}
3091
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003092const std::array<uint8_t, 32> InputDispatcher::getSignature(
3093 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3094 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3095 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3096 // Only sign events up and down events as the purely move events
3097 // are tied to their up/down counterparts so signing would be redundant.
3098 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3099 verifiedEvent.actionMasked = actionMasked;
3100 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003101 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003102 }
3103 return INVALID_HMAC;
3104}
3105
3106const std::array<uint8_t, 32> InputDispatcher::getSignature(
3107 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3108 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3109 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3110 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003111 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003112}
3113
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003115 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003116 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117#if DEBUG_DISPATCH_CYCLE
3118 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120#endif
3121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 if (connection->status == Connection::STATUS_BROKEN ||
3123 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 return;
3125 }
3126
3127 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003128 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129}
3130
3131void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 const sp<Connection>& connection,
3133 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134#if DEBUG_DISPATCH_CYCLE
3135 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137#endif
3138
3139 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003140 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003141 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003142 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003143 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144
3145 // The connection appears to be unrecoverably broken.
3146 // Ignore already broken or zombie connections.
3147 if (connection->status == Connection::STATUS_NORMAL) {
3148 connection->status = Connection::STATUS_BROKEN;
3149
3150 if (notify) {
3151 // Notify other system components.
3152 onDispatchCycleBrokenLocked(currentTime, connection);
3153 }
3154 }
3155}
3156
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003157void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3158 while (!queue.empty()) {
3159 DispatchEntry* dispatchEntry = queue.front();
3160 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003161 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
3163}
3164
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003165void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003167 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
3169 delete dispatchEntry;
3170}
3171
3172int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3173 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3174
3175 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003176 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003178 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 "fd=%d, events=0x%x",
3181 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 return 0; // remove the callback
3183 }
3184
3185 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003186 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3188 if (!(events & ALOOPER_EVENT_INPUT)) {
3189 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 "events=0x%x",
3191 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 return 1;
3193 }
3194
3195 nsecs_t currentTime = now();
3196 bool gotOne = false;
Siarhei Vishniakou4c92c5f2021-03-05 02:32:57 +00003197 status_t status = OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 for (;;) {
Siarhei Vishniakou4c92c5f2021-03-05 02:32:57 +00003199 Result<InputPublisher::Finished> result =
3200 connection->inputPublisher.receiveFinishedSignal();
3201 if (!result.ok()) {
3202 status = result.error().code();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 break;
3204 }
Siarhei Vishniakou4c92c5f2021-03-05 02:32:57 +00003205 const InputPublisher::Finished& finished = *result;
3206 d->finishDispatchCycleLocked(currentTime, connection, finished.seq,
3207 finished.handled, finished.consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 gotOne = true;
3209 }
3210 if (gotOne) {
3211 d->runCommandsLockedInterruptible();
3212 if (status == WOULD_BLOCK) {
3213 return 1;
3214 }
3215 }
3216
3217 notify = status != DEAD_OBJECT || !connection->monitor;
3218 if (notify) {
3219 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
3222 } else {
3223 // Monitor channels are never explicitly unregistered.
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003224 // We do it automatically when the remote endpoint is closed so don't warn about them.
arthurhungd352cb32020-04-28 17:09:28 +08003225 const bool stillHaveWindowHandle =
3226 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3227 nullptr;
3228 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 if (notify) {
3230 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 "events=0x%x",
3232 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 }
3234 }
3235
Garfield Tan15601662020-09-22 15:32:38 -07003236 // Remove the channel.
3237 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240}
3241
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003244 for (const auto& [fd, connection] : mConnectionsByFd) {
3245 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
3247}
3248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003249void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003250 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003251 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3252 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3253}
3254
3255void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3256 const CancelationOptions& options,
3257 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3258 for (const auto& it : monitorsByDisplay) {
3259 const std::vector<Monitor>& monitors = it.second;
3260 for (const Monitor& monitor : monitors) {
3261 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003262 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003263 }
3264}
3265
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003267 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003268 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003269 if (connection == nullptr) {
3270 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003272
3273 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274}
3275
3276void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3277 const sp<Connection>& connection, const CancelationOptions& options) {
3278 if (connection->status == Connection::STATUS_BROKEN) {
3279 return;
3280 }
3281
3282 nsecs_t currentTime = now();
3283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003284 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003285 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003287 if (cancelationEvents.empty()) {
3288 return;
3289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003291 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3292 "with reality: %s, mode=%d.",
3293 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3294 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003296
3297 InputTarget target;
3298 sp<InputWindowHandle> windowHandle =
3299 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3300 if (windowHandle != nullptr) {
3301 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003302 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003303 target.globalScaleFactor = windowInfo->globalScaleFactor;
3304 }
3305 target.inputChannel = connection->inputChannel;
3306 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3307
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003308 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003310 switch (cancelationEventEntry->type) {
3311 case EventEntry::Type::KEY: {
3312 logOutboundKeyDetails("cancel - ",
3313 static_cast<const KeyEntry&>(*cancelationEventEntry));
3314 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003316 case EventEntry::Type::MOTION: {
3317 logOutboundMotionDetails("cancel - ",
3318 static_cast<const MotionEntry&>(*cancelationEventEntry));
3319 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003321 case EventEntry::Type::FOCUS:
3322 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3323 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003324 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003325 break;
3326 }
3327 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003328 case EventEntry::Type::DEVICE_RESET:
3329 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003330 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003331 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003332 break;
3333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 }
3335
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003336 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3337 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003339
3340 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341}
3342
Svet Ganov5d3bc372020-01-26 23:11:07 -08003343void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3344 const sp<Connection>& connection) {
3345 if (connection->status == Connection::STATUS_BROKEN) {
3346 return;
3347 }
3348
3349 nsecs_t currentTime = now();
3350
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003351 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003352 connection->inputState.synthesizePointerDownEvents(currentTime);
3353
3354 if (downEvents.empty()) {
3355 return;
3356 }
3357
3358#if DEBUG_OUTBOUND_EVENT_DETAILS
3359 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3360 connection->getInputChannelName().c_str(), downEvents.size());
3361#endif
3362
3363 InputTarget target;
3364 sp<InputWindowHandle> windowHandle =
3365 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3366 if (windowHandle != nullptr) {
3367 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003368 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003369 target.globalScaleFactor = windowInfo->globalScaleFactor;
3370 }
3371 target.inputChannel = connection->inputChannel;
3372 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3373
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003374 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003375 switch (downEventEntry->type) {
3376 case EventEntry::Type::MOTION: {
3377 logOutboundMotionDetails("down - ",
3378 static_cast<const MotionEntry&>(*downEventEntry));
3379 break;
3380 }
3381
3382 case EventEntry::Type::KEY:
3383 case EventEntry::Type::FOCUS:
3384 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003385 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003386 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3387 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003388 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003389 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003390 break;
3391 }
3392 }
3393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003394 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3395 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003396 }
3397
3398 startDispatchCycleLocked(currentTime, connection);
3399}
3400
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003401std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3402 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 ALOG_ASSERT(pointerIds.value != 0);
3404
3405 uint32_t splitPointerIndexMap[MAX_POINTERS];
3406 PointerProperties splitPointerProperties[MAX_POINTERS];
3407 PointerCoords splitPointerCoords[MAX_POINTERS];
3408
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003409 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 uint32_t splitPointerCount = 0;
3411
3412 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003413 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003415 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 uint32_t pointerId = uint32_t(pointerProperties.id);
3417 if (pointerIds.hasBit(pointerId)) {
3418 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3419 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3420 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003421 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 splitPointerCount += 1;
3423 }
3424 }
3425
3426 if (splitPointerCount != pointerIds.count()) {
3427 // This is bad. We are missing some of the pointers that we expected to deliver.
3428 // Most likely this indicates that we received an ACTION_MOVE events that has
3429 // different pointer ids than we expected based on the previous ACTION_DOWN
3430 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3431 // in this way.
3432 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003433 "we expected there to be %d pointers. This probably means we received "
3434 "a broken sequence of pointer ids from the input device.",
3435 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003436 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 }
3438
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003439 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3442 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3444 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003445 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 uint32_t pointerId = uint32_t(pointerProperties.id);
3447 if (pointerIds.hasBit(pointerId)) {
3448 if (pointerIds.count() == 1) {
3449 // The first/last pointer went down/up.
3450 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003452 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3453 ? AMOTION_EVENT_ACTION_CANCEL
3454 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 } else {
3456 // A secondary pointer went down/up.
3457 uint32_t splitPointerIndex = 0;
3458 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3459 splitPointerIndex += 1;
3460 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 action = maskedAction |
3462 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
3464 } else {
3465 // An unrelated pointer changed.
3466 action = AMOTION_EVENT_ACTION_MOVE;
3467 }
3468 }
3469
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003470 int32_t newId = mIdGenerator.nextId();
3471 if (ATRACE_ENABLED()) {
3472 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3473 ") to MotionEvent(id=0x%" PRIx32 ").",
3474 originalMotionEntry.id, newId);
3475 ATRACE_NAME(message.c_str());
3476 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003477 std::unique_ptr<MotionEntry> splitMotionEntry =
3478 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3479 originalMotionEntry.deviceId, originalMotionEntry.source,
3480 originalMotionEntry.displayId,
3481 originalMotionEntry.policyFlags, action,
3482 originalMotionEntry.actionButton,
3483 originalMotionEntry.flags, originalMotionEntry.metaState,
3484 originalMotionEntry.buttonState,
3485 originalMotionEntry.classification,
3486 originalMotionEntry.edgeFlags,
3487 originalMotionEntry.xPrecision,
3488 originalMotionEntry.yPrecision,
3489 originalMotionEntry.xCursorPosition,
3490 originalMotionEntry.yCursorPosition,
3491 originalMotionEntry.downTime, splitPointerCount,
3492 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003494 if (originalMotionEntry.injectionState) {
3495 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 splitMotionEntry->injectionState->refCount += 1;
3497 }
3498
3499 return splitMotionEntry;
3500}
3501
3502void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3503#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003504 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505#endif
3506
3507 bool needWake;
3508 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003509 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003511 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3512 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3513 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 } // release lock
3515
3516 if (needWake) {
3517 mLooper->wake();
3518 }
3519}
3520
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003521/**
3522 * If one of the meta shortcuts is detected, process them here:
3523 * Meta + Backspace -> generate BACK
3524 * Meta + Enter -> generate HOME
3525 * This will potentially overwrite keyCode and metaState.
3526 */
3527void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003528 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003529 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3530 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3531 if (keyCode == AKEYCODE_DEL) {
3532 newKeyCode = AKEYCODE_BACK;
3533 } else if (keyCode == AKEYCODE_ENTER) {
3534 newKeyCode = AKEYCODE_HOME;
3535 }
3536 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003537 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003538 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003539 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003540 keyCode = newKeyCode;
3541 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3542 }
3543 } else if (action == AKEY_EVENT_ACTION_UP) {
3544 // In order to maintain a consistent stream of up and down events, check to see if the key
3545 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3546 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003547 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003548 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003549 auto replacementIt = mReplacedKeys.find(replacement);
3550 if (replacementIt != mReplacedKeys.end()) {
3551 keyCode = replacementIt->second;
3552 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003553 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3554 }
3555 }
3556}
3557
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3559#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003560 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3561 "policyFlags=0x%x, action=0x%x, "
3562 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3563 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3564 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3565 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566#endif
3567 if (!validateKeyEvent(args->action)) {
3568 return;
3569 }
3570
3571 uint32_t policyFlags = args->policyFlags;
3572 int32_t flags = args->flags;
3573 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003574 // InputDispatcher tracks and generates key repeats on behalf of
3575 // whatever notifies it, so repeatCount should always be set to 0
3576 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3578 policyFlags |= POLICY_FLAG_VIRTUAL;
3579 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 if (policyFlags & POLICY_FLAG_FUNCTION) {
3582 metaState |= AMETA_FUNCTION_ON;
3583 }
3584
3585 policyFlags |= POLICY_FLAG_TRUSTED;
3586
Michael Wright78f24442014-08-06 15:55:28 -07003587 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003588 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003589
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003591 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003592 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3593 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
Michael Wright2b3c3302018-03-02 17:19:13 +00003595 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003597 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3598 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003599 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 bool needWake;
3603 { // acquire lock
3604 mLock.lock();
3605
3606 if (shouldSendKeyToInputFilterLocked(args)) {
3607 mLock.unlock();
3608
3609 policyFlags |= POLICY_FLAG_FILTERED;
3610 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3611 return; // event was consumed by the filter
3612 }
3613
3614 mLock.lock();
3615 }
3616
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003617 std::unique_ptr<KeyEntry> newEntry =
3618 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3619 args->displayId, policyFlags, args->action, flags,
3620 keyCode, args->scanCode, metaState, repeatCount,
3621 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003623 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 mLock.unlock();
3625 } // release lock
3626
3627 if (needWake) {
3628 mLooper->wake();
3629 }
3630}
3631
3632bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3633 return mInputFilterEnabled;
3634}
3635
3636void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3637#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003638 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3639 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003640 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3641 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003642 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003643 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3644 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3645 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3646 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 for (uint32_t i = 0; i < args->pointerCount; i++) {
3648 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003649 "x=%f, y=%f, pressure=%f, size=%f, "
3650 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3651 "orientation=%f",
3652 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3653 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003664 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3665 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 return;
3667 }
3668
3669 uint32_t policyFlags = args->policyFlags;
3670 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003671
3672 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003673 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003674 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3675 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678
3679 bool needWake;
3680 { // acquire lock
3681 mLock.lock();
3682
3683 if (shouldSendMotionToInputFilterLocked(args)) {
3684 mLock.unlock();
3685
3686 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003687 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003688 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3689 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003690 args->metaState, args->buttonState, args->classification, transform,
3691 args->xPrecision, args->yPrecision, args->xCursorPosition,
3692 args->yCursorPosition, args->downTime, args->eventTime,
3693 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694
3695 policyFlags |= POLICY_FLAG_FILTERED;
3696 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3697 return; // event was consumed by the filter
3698 }
3699
3700 mLock.lock();
3701 }
3702
3703 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 std::unique_ptr<MotionEntry> newEntry =
3705 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3706 args->source, args->displayId, policyFlags,
3707 args->action, args->actionButton, args->flags,
3708 args->metaState, args->buttonState,
3709 args->classification, args->edgeFlags,
3710 args->xPrecision, args->yPrecision,
3711 args->xCursorPosition, args->yCursorPosition,
3712 args->downTime, args->pointerCount,
3713 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003715 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 mLock.unlock();
3717 } // release lock
3718
3719 if (needWake) {
3720 mLooper->wake();
3721 }
3722}
3723
Chris Yef59a2f42020-10-16 12:55:26 -07003724void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3725#if DEBUG_INBOUND_EVENT_DETAILS
3726 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3727 " sensorType=%s",
3728 args->id, args->eventTime, args->deviceId, args->source,
3729 NamedEnum::string(args->sensorType).c_str());
3730#endif
3731
3732 bool needWake;
3733 { // acquire lock
3734 mLock.lock();
3735
3736 // Just enqueue a new sensor event.
3737 std::unique_ptr<SensorEntry> newEntry =
3738 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3739 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3740 args->sensorType, args->accuracy,
3741 args->accuracyChanged, args->values);
3742
3743 needWake = enqueueInboundEventLocked(std::move(newEntry));
3744 mLock.unlock();
3745 } // release lock
3746
3747 if (needWake) {
3748 mLooper->wake();
3749 }
3750}
3751
Chris Yefb552902021-02-03 17:18:37 -08003752void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3753#if DEBUG_INBOUND_EVENT_DETAILS
3754 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3755 args->deviceId, args->isOn);
3756#endif
3757 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3758}
3759
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003761 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762}
3763
3764void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3765#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003766 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003767 "switchMask=0x%08x",
3768 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769#endif
3770
3771 uint32_t policyFlags = args->policyFlags;
3772 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003773 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774}
3775
3776void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3777#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003778 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3779 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780#endif
3781
3782 bool needWake;
3783 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003784 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003786 std::unique_ptr<DeviceResetEntry> newEntry =
3787 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3788 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 } // release lock
3790
3791 if (needWake) {
3792 mLooper->wake();
3793 }
3794}
3795
Prabir Pradhan7e186182020-11-10 13:56:45 -08003796void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3797#if DEBUG_INBOUND_EVENT_DETAILS
3798 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3799 args->enabled ? "true" : "false");
3800#endif
3801
Prabir Pradhan99987712020-11-10 18:43:05 -08003802 bool needWake;
3803 { // acquire lock
3804 std::scoped_lock _l(mLock);
3805 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3806 args->enabled);
3807 needWake = enqueueInboundEventLocked(std::move(entry));
3808 } // release lock
3809
3810 if (needWake) {
3811 mLooper->wake();
3812 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003813}
3814
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003815InputEventInjectionResult InputDispatcher::injectInputEvent(
3816 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3817 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818#if DEBUG_INBOUND_EVENT_DETAILS
3819 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003820 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3821 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003823 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824
3825 policyFlags |= POLICY_FLAG_INJECTED;
3826 if (hasInjectionPermission(injectorPid, injectorUid)) {
3827 policyFlags |= POLICY_FLAG_TRUSTED;
3828 }
3829
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003830 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003833 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3834 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003835 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003836 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003839 int32_t flags = incomingKey.getFlags();
3840 int32_t keyCode = incomingKey.getKeyCode();
3841 int32_t metaState = incomingKey.getMetaState();
3842 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003843 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003844 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003845 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003846 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3847 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3848 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3851 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003852 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003853
3854 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3855 android::base::Timer t;
3856 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3857 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3858 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3859 std::to_string(t.duration().count()).c_str());
3860 }
3861 }
3862
3863 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003864 std::unique_ptr<KeyEntry> injectedEntry =
3865 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3866 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3867 incomingKey.getDisplayId(), policyFlags, action,
3868 flags, keyCode, incomingKey.getScanCode(), metaState,
3869 incomingKey.getRepeatCount(),
3870 incomingKey.getDownTime());
3871 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 }
3874
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 case AINPUT_EVENT_TYPE_MOTION: {
3876 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3877 int32_t action = motionEvent->getAction();
3878 size_t pointerCount = motionEvent->getPointerCount();
3879 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3880 int32_t actionButton = motionEvent->getActionButton();
3881 int32_t displayId = motionEvent->getDisplayId();
3882 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003883 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003884 }
3885
3886 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3887 nsecs_t eventTime = motionEvent->getEventTime();
3888 android::base::Timer t;
3889 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3890 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3891 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3892 std::to_string(t.duration().count()).c_str());
3893 }
3894 }
3895
3896 mLock.lock();
3897 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3898 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003899 std::unique_ptr<MotionEntry> injectedEntry =
3900 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3901 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3902 motionEvent->getDisplayId(), policyFlags, action,
3903 actionButton, motionEvent->getFlags(),
3904 motionEvent->getMetaState(),
3905 motionEvent->getButtonState(),
3906 motionEvent->getClassification(),
3907 motionEvent->getEdgeFlags(),
3908 motionEvent->getXPrecision(),
3909 motionEvent->getYPrecision(),
3910 motionEvent->getRawXCursorPosition(),
3911 motionEvent->getRawYCursorPosition(),
3912 motionEvent->getDownTime(),
3913 uint32_t(pointerCount), pointerProperties,
3914 samplePointerCoords, motionEvent->getXOffset(),
3915 motionEvent->getYOffset());
3916 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003917 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3918 sampleEventTimes += 1;
3919 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003920 std::unique_ptr<MotionEntry> nextInjectedEntry =
3921 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3922 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3923 motionEvent->getDisplayId(), policyFlags,
3924 action, actionButton, motionEvent->getFlags(),
3925 motionEvent->getMetaState(),
3926 motionEvent->getButtonState(),
3927 motionEvent->getClassification(),
3928 motionEvent->getEdgeFlags(),
3929 motionEvent->getXPrecision(),
3930 motionEvent->getYPrecision(),
3931 motionEvent->getRawXCursorPosition(),
3932 motionEvent->getRawYCursorPosition(),
3933 motionEvent->getDownTime(),
3934 uint32_t(pointerCount), pointerProperties,
3935 samplePointerCoords,
3936 motionEvent->getXOffset(),
3937 motionEvent->getYOffset());
3938 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003939 }
3940 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003943 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003944 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003945 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 }
3947
3948 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003949 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 injectionState->injectionIsAsync = true;
3951 }
3952
3953 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003954 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
3956 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003957 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003958 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003959 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 }
3961
3962 mLock.unlock();
3963
3964 if (needWake) {
3965 mLooper->wake();
3966 }
3967
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003968 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003970 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003972 if (syncMode == InputEventInjectionSync::NONE) {
3973 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 } else {
3975 for (;;) {
3976 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003977 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 break;
3979 }
3980
3981 nsecs_t remainingTimeout = endTime - now();
3982 if (remainingTimeout <= 0) {
3983#if DEBUG_INJECTION
3984 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003985 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003987 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 break;
3989 }
3990
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003991 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003994 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3995 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 while (injectionState->pendingForegroundDispatches != 0) {
3997#if DEBUG_INJECTION
3998 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003999 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000#endif
4001 nsecs_t remainingTimeout = endTime - now();
4002 if (remainingTimeout <= 0) {
4003#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4005 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004007 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 break;
4009 }
4010
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004011 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 }
4013 }
4014 }
4015
4016 injectionState->release();
4017 } // release lock
4018
4019#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004020 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004021 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022#endif
4023
4024 return injectionResult;
4025}
4026
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004027std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004028 std::array<uint8_t, 32> calculatedHmac;
4029 std::unique_ptr<VerifiedInputEvent> result;
4030 switch (event.getType()) {
4031 case AINPUT_EVENT_TYPE_KEY: {
4032 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4033 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4034 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004035 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004036 break;
4037 }
4038 case AINPUT_EVENT_TYPE_MOTION: {
4039 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4040 VerifiedMotionEvent verifiedMotionEvent =
4041 verifiedMotionEventFromMotionEvent(motionEvent);
4042 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004043 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004044 break;
4045 }
4046 default: {
4047 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4048 return nullptr;
4049 }
4050 }
4051 if (calculatedHmac == INVALID_HMAC) {
4052 return nullptr;
4053 }
4054 if (calculatedHmac != event.getHmac()) {
4055 return nullptr;
4056 }
4057 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004058}
4059
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061 return injectorUid == 0 ||
4062 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063}
4064
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004065void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004066 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004067 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 if (injectionState) {
4069#if DEBUG_INJECTION
4070 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 "injectorPid=%d, injectorUid=%d",
4072 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073#endif
4074
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004075 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 // Log the outcome since the injector did not wait for the injection result.
4077 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004078 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 ALOGV("Asynchronous input event injection succeeded.");
4080 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004081 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004082 ALOGW("Asynchronous input event injection failed.");
4083 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004084 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 ALOGW("Asynchronous input event injection permission denied.");
4086 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004087 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004088 ALOGW("Asynchronous input event injection timed out.");
4089 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004090 case InputEventInjectionResult::PENDING:
4091 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4092 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 }
4094 }
4095
4096 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004097 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
4099}
4100
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004101void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4102 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 if (injectionState) {
4104 injectionState->pendingForegroundDispatches += 1;
4105 }
4106}
4107
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4109 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 if (injectionState) {
4111 injectionState->pendingForegroundDispatches -= 1;
4112
4113 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004114 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 }
4116 }
4117}
4118
Vishnu Nairad321cd2020-08-20 16:40:21 -07004119const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004120 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004121 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4122 auto it = mWindowHandlesByDisplay.find(displayId);
4123 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004124}
4125
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004127 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004128 if (windowHandleToken == nullptr) {
4129 return nullptr;
4130 }
4131
Arthur Hungb92218b2018-08-14 12:00:21 +08004132 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004133 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004134 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004135 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004136 return windowHandle;
4137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 }
4139 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004140 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141}
4142
Vishnu Nairad321cd2020-08-20 16:40:21 -07004143sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4144 int displayId) const {
4145 if (windowHandleToken == nullptr) {
4146 return nullptr;
4147 }
4148
4149 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4150 if (windowHandle->getToken() == windowHandleToken) {
4151 return windowHandle;
4152 }
4153 }
4154 return nullptr;
4155}
4156
4157sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Vishnu Nairc519ff72021-01-21 08:23:08 -08004158 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004159 return getWindowHandleLocked(focusedToken, displayId);
4160}
4161
Mady Mellor017bcd12020-06-23 19:12:00 +00004162bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4163 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004164 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004165 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004166 if (handle->getId() == windowHandle->getId() &&
4167 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004168 if (windowHandle->getInfo()->displayId != it.first) {
4169 ALOGE("Found window %s in display %" PRId32
4170 ", but it should belong to display %" PRId32,
4171 windowHandle->getName().c_str(), it.first,
4172 windowHandle->getInfo()->displayId);
4173 }
4174 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 }
4177 }
4178 return false;
4179}
4180
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004181bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4182 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4183 const bool noInputChannel =
4184 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4185 if (connection != nullptr && noInputChannel) {
4186 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4187 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4188 return false;
4189 }
4190
4191 if (connection == nullptr) {
4192 if (!noInputChannel) {
4193 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4194 }
4195 return false;
4196 }
4197 if (!connection->responsive) {
4198 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4199 return false;
4200 }
4201 return true;
4202}
4203
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004204std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4205 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004206 size_t count = mInputChannelsByToken.count(token);
4207 if (count == 0) {
4208 return nullptr;
4209 }
4210 return mInputChannelsByToken.at(token);
4211}
4212
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004213void InputDispatcher::updateWindowHandlesForDisplayLocked(
4214 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4215 if (inputWindowHandles.empty()) {
4216 // Remove all handles on a display if there are no windows left.
4217 mWindowHandlesByDisplay.erase(displayId);
4218 return;
4219 }
4220
4221 // Since we compare the pointer of input window handles across window updates, we need
4222 // to make sure the handle object for the same window stays unchanged across updates.
4223 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004224 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004225 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004226 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004227 }
4228
4229 std::vector<sp<InputWindowHandle>> newHandles;
4230 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4231 if (!handle->updateInfo()) {
4232 // handle no longer valid
4233 continue;
4234 }
4235
4236 const InputWindowInfo* info = handle->getInfo();
4237 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4238 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4239 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004240 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4241 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4242 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004243 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004244 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004245 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004246 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004247 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004248 }
4249
4250 if (info->displayId != displayId) {
4251 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4252 handle->getName().c_str(), displayId, info->displayId);
4253 continue;
4254 }
4255
Robert Carredd13602020-04-13 17:24:34 -07004256 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4257 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004258 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004259 oldHandle->updateFrom(handle);
4260 newHandles.push_back(oldHandle);
4261 } else {
4262 newHandles.push_back(handle);
4263 }
4264 }
4265
4266 // Insert or replace
4267 mWindowHandlesByDisplay[displayId] = newHandles;
4268}
4269
Arthur Hung72d8dc32020-03-28 00:48:39 +00004270void InputDispatcher::setInputWindows(
4271 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4272 { // acquire lock
4273 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004274 for (const auto& [displayId, handles] : handlesPerDisplay) {
4275 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004276 }
4277 }
4278 // Wake up poll loop since it may need to make new input dispatching choices.
4279 mLooper->wake();
4280}
4281
Arthur Hungb92218b2018-08-14 12:00:21 +08004282/**
4283 * Called from InputManagerService, update window handle list by displayId that can receive input.
4284 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4285 * If set an empty list, remove all handles from the specific display.
4286 * For focused handle, check if need to change and send a cancel event to previous one.
4287 * For removed handle, check if need to send a cancel event if already in touch.
4288 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004289void InputDispatcher::setInputWindowsLocked(
4290 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004291 if (DEBUG_FOCUS) {
4292 std::string windowList;
4293 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4294 windowList += iwh->getName() + " ";
4295 }
4296 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004299 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4300 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4301 const bool noInputWindow =
4302 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4303 if (noInputWindow && window->getToken() != nullptr) {
4304 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4305 window->getName().c_str());
4306 window->releaseChannel();
4307 }
4308 }
4309
Arthur Hung72d8dc32020-03-28 00:48:39 +00004310 // Copy old handles for release if they are no longer present.
4311 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312
Arthur Hung72d8dc32020-03-28 00:48:39 +00004313 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004314
Vishnu Nair958da932020-08-21 17:12:37 -07004315 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4316 if (mLastHoverWindowHandle &&
4317 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4318 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004319 mLastHoverWindowHandle = nullptr;
4320 }
4321
Vishnu Nairc519ff72021-01-21 08:23:08 -08004322 std::optional<FocusResolver::FocusChanges> changes =
4323 mFocusResolver.setInputWindows(displayId, windowHandles);
4324 if (changes) {
4325 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004328 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4329 mTouchStatesByDisplay.find(displayId);
4330 if (stateIt != mTouchStatesByDisplay.end()) {
4331 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004332 for (size_t i = 0; i < state.windows.size();) {
4333 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004334 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004335 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004336 ALOGD("Touched window was removed: %s in display %" PRId32,
4337 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004338 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004339 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004340 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4341 if (touchedInputChannel != nullptr) {
4342 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4343 "touched window was removed");
4344 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004346 state.windows.erase(state.windows.begin() + i);
4347 } else {
4348 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 }
4350 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004351 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004352
Arthur Hung72d8dc32020-03-28 00:48:39 +00004353 // Release information for windows that are no longer present.
4354 // This ensures that unused input channels are released promptly.
4355 // Otherwise, they might stick around until the window handle is destroyed
4356 // which might not happen until the next GC.
4357 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004358 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004359 if (DEBUG_FOCUS) {
4360 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004361 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004362 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004363 // To avoid making too many calls into the compat framework, only
4364 // check for window flags when windows are going away.
4365 // TODO(b/157929241) : delete this. This is only needed temporarily
4366 // in order to gather some data about the flag usage
4367 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4368 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4369 oldWindowHandle->getName().c_str());
4370 if (mCompatService != nullptr) {
4371 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4372 oldWindowHandle->getInfo()->ownerUid);
4373 }
4374 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004375 }
chaviw291d88a2019-02-14 10:33:58 -08004376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377}
4378
4379void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004380 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004381 if (DEBUG_FOCUS) {
4382 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4383 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4384 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004385 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004386 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387
Chris Yea209fde2020-07-22 13:54:51 -07004388 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004389 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004390
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004391 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4392 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004393 }
4394
Chris Yea209fde2020-07-22 13:54:51 -07004395 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004396 if (inputApplicationHandle != nullptr) {
4397 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4398 } else {
4399 mFocusedApplicationHandlesByDisplay.erase(displayId);
4400 }
4401
4402 // No matter what the old focused application was, stop waiting on it because it is
4403 // no longer focused.
4404 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 } // release lock
4406
4407 // Wake up poll loop since it may need to make new input dispatching choices.
4408 mLooper->wake();
4409}
4410
Tiger Huang721e26f2018-07-24 22:26:19 +08004411/**
4412 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4413 * the display not specified.
4414 *
4415 * We track any unreleased events for each window. If a window loses the ability to receive the
4416 * released event, we will send a cancel event to it. So when the focused display is changed, we
4417 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4418 * display. The display-specified events won't be affected.
4419 */
4420void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004421 if (DEBUG_FOCUS) {
4422 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4423 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004424 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004425 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004426
4427 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004428 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004429 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004430 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004431 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004432 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004433 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004434 CancelationOptions
4435 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4436 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004437 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004438 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4439 }
4440 }
4441 mFocusedDisplayId = displayId;
4442
Chris Ye3c2d6f52020-08-09 10:39:48 -07004443 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004444 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004445 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004446
Vishnu Nairad321cd2020-08-20 16:40:21 -07004447 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004448 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004449 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004450 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004451 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004452 }
4453 }
4454 }
4455
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004456 if (DEBUG_FOCUS) {
4457 logDispatchStateLocked();
4458 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004459 } // release lock
4460
4461 // Wake up poll loop since it may need to make new input dispatching choices.
4462 mLooper->wake();
4463}
4464
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004466 if (DEBUG_FOCUS) {
4467 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469
4470 bool changed;
4471 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004472 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
4474 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4475 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004476 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 }
4478
4479 if (mDispatchEnabled && !enabled) {
4480 resetAndDropEverythingLocked("dispatcher is being disabled");
4481 }
4482
4483 mDispatchEnabled = enabled;
4484 mDispatchFrozen = frozen;
4485 changed = true;
4486 } else {
4487 changed = false;
4488 }
4489
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004490 if (DEBUG_FOCUS) {
4491 logDispatchStateLocked();
4492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 } // release lock
4494
4495 if (changed) {
4496 // Wake up poll loop since it may need to make new input dispatching choices.
4497 mLooper->wake();
4498 }
4499}
4500
4501void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004502 if (DEBUG_FOCUS) {
4503 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505
4506 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004507 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
4509 if (mInputFilterEnabled == enabled) {
4510 return;
4511 }
4512
4513 mInputFilterEnabled = enabled;
4514 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4515 } // release lock
4516
4517 // Wake up poll loop since there might be work to do to drop everything.
4518 mLooper->wake();
4519}
4520
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004521void InputDispatcher::setInTouchMode(bool inTouchMode) {
4522 std::scoped_lock lock(mLock);
4523 mInTouchMode = inTouchMode;
4524}
4525
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004526void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4527 if (opacity < 0 || opacity > 1) {
4528 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4529 return;
4530 }
4531
4532 std::scoped_lock lock(mLock);
4533 mMaximumObscuringOpacityForTouch = opacity;
4534}
4535
4536void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4537 std::scoped_lock lock(mLock);
4538 mBlockUntrustedTouchesMode = mode;
4539}
4540
chaviwfbe5d9c2018-12-26 12:23:37 -08004541bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4542 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004543 if (DEBUG_FOCUS) {
4544 ALOGD("Trivial transfer to same window.");
4545 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004546 return true;
4547 }
4548
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004550 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551
chaviwfbe5d9c2018-12-26 12:23:37 -08004552 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4553 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004554 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004555 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 return false;
4557 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004558 if (DEBUG_FOCUS) {
4559 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4560 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004563 if (DEBUG_FOCUS) {
4564 ALOGD("Cannot transfer focus because windows are on different displays.");
4565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 return false;
4567 }
4568
4569 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004570 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4571 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004572 for (size_t i = 0; i < state.windows.size(); i++) {
4573 const TouchedWindow& touchedWindow = state.windows[i];
4574 if (touchedWindow.windowHandle == fromWindowHandle) {
4575 int32_t oldTargetFlags = touchedWindow.targetFlags;
4576 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004578 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004580 int32_t newTargetFlags = oldTargetFlags &
4581 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4582 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004583 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584
Jeff Brownf086ddb2014-02-11 14:28:48 -08004585 found = true;
4586 goto Found;
4587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 }
4589 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004590 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004592 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004593 if (DEBUG_FOCUS) {
4594 ALOGD("Focus transfer failed because from window did not have focus.");
4595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 return false;
4597 }
4598
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004599 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4600 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004601 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004602 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004603 CancelationOptions
4604 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4605 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004607 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 }
4609
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004610 if (DEBUG_FOCUS) {
4611 logDispatchStateLocked();
4612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 } // release lock
4614
4615 // Wake up poll loop since it may need to make new input dispatching choices.
4616 mLooper->wake();
4617 return true;
4618}
4619
4620void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004621 if (DEBUG_FOCUS) {
4622 ALOGD("Resetting and dropping all events (%s).", reason);
4623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624
4625 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4626 synthesizeCancelationEventsForAllConnectionsLocked(options);
4627
4628 resetKeyRepeatLocked();
4629 releasePendingEventLocked();
4630 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004633 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004634 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004636 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637}
4638
4639void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004640 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 dumpDispatchStateLocked(dump);
4642
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004643 std::istringstream stream(dump);
4644 std::string line;
4645
4646 while (std::getline(stream, line, '\n')) {
4647 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648 }
4649}
4650
Prabir Pradhan99987712020-11-10 18:43:05 -08004651std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4652 std::string dump;
4653
4654 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4655 toString(mFocusedWindowRequestedPointerCapture));
4656
4657 std::string windowName = "None";
4658 if (mWindowTokenWithPointerCapture) {
4659 const sp<InputWindowHandle> captureWindowHandle =
4660 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4661 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4662 : "token has capture without window";
4663 }
4664 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4665
4666 return dump;
4667}
4668
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004669void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004670 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4671 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4672 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004673 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674
Tiger Huang721e26f2018-07-24 22:26:19 +08004675 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4676 dump += StringPrintf(INDENT "FocusedApplications:\n");
4677 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4678 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004679 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004680 const std::chrono::duration timeout =
4681 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004682 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004683 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004684 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004687 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004689
Vishnu Nairc519ff72021-01-21 08:23:08 -08004690 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004691 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004693 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004694 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004695 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4696 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004697 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004698 state.displayId, toString(state.down), toString(state.split),
4699 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004700 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004701 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004702 for (size_t i = 0; i < state.windows.size(); i++) {
4703 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004704 dump += StringPrintf(INDENT4
4705 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4706 i, touchedWindow.windowHandle->getName().c_str(),
4707 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004708 }
4709 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004710 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004711 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004712 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004713 dump += INDENT3 "Portal windows:\n";
4714 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004715 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004716 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4717 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004718 }
4719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 }
4721 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004722 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 }
4724
Arthur Hungb92218b2018-08-14 12:00:21 +08004725 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004726 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004727 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004728 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004729 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004730 dump += INDENT2 "Windows:\n";
4731 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004732 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004733 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004735 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004736 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004737 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004738 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004739 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004740 "applicationInfo.name=%s, "
4741 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004742 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004743 i, windowInfo->name.c_str(), windowInfo->id,
4744 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004745 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004746 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004747 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004748 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004749 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004750 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004751 windowInfo->frameLeft, windowInfo->frameTop,
4752 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004753 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004754 windowInfo->applicationInfo.name.c_str(),
4755 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004756 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004757 dump += StringPrintf(", inputFeatures=%s",
4758 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004759 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004760 "ms, trustedOverlay=%s, hasToken=%s, "
4761 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004762 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004763 millis(windowInfo->dispatchingTimeout),
4764 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004765 toString(windowInfo->token != nullptr),
4766 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004767 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004768 }
4769 } else {
4770 dump += INDENT2 "Windows: <none>\n";
4771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004774 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 }
4776
Michael Wright3dd60e22019-03-27 22:06:44 +00004777 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004778 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004779 const std::vector<Monitor>& monitors = it.second;
4780 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4781 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004782 }
4783 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004784 const std::vector<Monitor>& monitors = it.second;
4785 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4786 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004789 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 }
4791
4792 nsecs_t currentTime = now();
4793
4794 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004795 if (!mRecentQueue.empty()) {
4796 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004797 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004798 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004799 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004800 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004803 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 }
4805
4806 // Dump event currently being dispatched.
4807 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004808 dump += INDENT "PendingEvent:\n";
4809 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004810 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004811 dump += StringPrintf(", age=%" PRId64 "ms\n",
4812 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004814 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 }
4816
4817 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004818 if (!mInboundQueue.empty()) {
4819 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004820 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004821 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004822 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004823 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 }
4825 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004826 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
4828
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004829 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004830 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004831 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4832 const KeyReplacement& replacement = pair.first;
4833 int32_t newKeyCode = pair.second;
4834 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004835 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004836 }
4837 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004838 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004839 }
4840
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004841 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004842 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004843 for (const auto& pair : mConnectionsByFd) {
4844 const sp<Connection>& connection = pair.second;
4845 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004847 pair.first, connection->getInputChannelName().c_str(),
4848 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004851 if (!connection->outboundQueue.empty()) {
4852 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4853 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004854 dump += dumpQueue(connection->outboundQueue, currentTime);
4855
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004857 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 }
4859
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004860 if (!connection->waitQueue.empty()) {
4861 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4862 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004863 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004865 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 }
4867 }
4868 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004869 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 }
4871
4872 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004873 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4874 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004876 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
4878
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004879 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004880 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4881 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4882 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883}
4884
Michael Wright3dd60e22019-03-27 22:06:44 +00004885void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4886 const size_t numMonitors = monitors.size();
4887 for (size_t i = 0; i < numMonitors; i++) {
4888 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004889 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004890 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4891 dump += "\n";
4892 }
4893}
4894
Siarhei Vishniakou4c92c5f2021-03-05 02:32:57 +00004895Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07004896#if DEBUG_CHANNEL_CREATION
4897 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898#endif
4899
Garfield Tan15601662020-09-22 15:32:38 -07004900 std::shared_ptr<InputChannel> serverChannel;
4901 std::unique_ptr<InputChannel> clientChannel;
4902 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4903
4904 if (result) {
4905 return base::Error(result) << "Failed to open input channel pair with name " << name;
4906 }
4907
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004909 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004910 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911
Garfield Tan15601662020-09-22 15:32:38 -07004912 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004913 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004914 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4917 } // release lock
4918
4919 // Wake the looper because some connections have changed.
4920 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004921 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922}
4923
Siarhei Vishniakou4c92c5f2021-03-05 02:32:57 +00004924Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
4925 bool isGestureMonitor,
4926 const std::string& name,
4927 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004928 std::shared_ptr<InputChannel> serverChannel;
4929 std::unique_ptr<InputChannel> clientChannel;
4930 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4931 if (result) {
4932 return base::Error(result) << "Failed to open input channel pair with name " << name;
4933 }
4934
Michael Wright3dd60e22019-03-27 22:06:44 +00004935 { // acquire lock
4936 std::scoped_lock _l(mLock);
4937
4938 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004939 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4940 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004941 }
4942
Garfield Tan15601662020-09-22 15:32:38 -07004943 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004944
Garfield Tan15601662020-09-22 15:32:38 -07004945 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004946 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004947 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004949 auto& monitorsByDisplay =
4950 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004951 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004952
4953 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004954 }
Garfield Tan15601662020-09-22 15:32:38 -07004955
Michael Wright3dd60e22019-03-27 22:06:44 +00004956 // Wake the looper because some connections have changed.
4957 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004958 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004959}
4960
Garfield Tan15601662020-09-22 15:32:38 -07004961status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004963 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964
Garfield Tan15601662020-09-22 15:32:38 -07004965 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 if (status) {
4967 return status;
4968 }
4969 } // release lock
4970
4971 // Wake the poll loop because removing the connection may have changed the current
4972 // synchronization state.
4973 mLooper->wake();
4974 return OK;
4975}
4976
Garfield Tan15601662020-09-22 15:32:38 -07004977status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4978 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004979 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004980 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00004981 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 return BAD_VALUE;
4983 }
4984
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004985 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004986 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004987
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004989 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 }
4991
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004992 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993
4994 nsecs_t currentTime = now();
4995 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4996
4997 connection->status = Connection::STATUS_ZOMBIE;
4998 return OK;
4999}
5000
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005001void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5002 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5003 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005004}
5005
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005006void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005007 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005008 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005009 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005010 std::vector<Monitor>& monitors = it->second;
5011 const size_t numMonitors = monitors.size();
5012 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005013 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005014 monitors.erase(monitors.begin() + i);
5015 break;
5016 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005017 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005018 if (monitors.empty()) {
5019 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005020 } else {
5021 ++it;
5022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023 }
5024}
5025
Michael Wright3dd60e22019-03-27 22:06:44 +00005026status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5027 { // acquire lock
5028 std::scoped_lock _l(mLock);
5029 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5030
5031 if (!foundDisplayId) {
5032 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5033 return BAD_VALUE;
5034 }
5035 int32_t displayId = foundDisplayId.value();
5036
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005037 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5038 mTouchStatesByDisplay.find(displayId);
5039 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005040 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5041 return BAD_VALUE;
5042 }
5043
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005044 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005045 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005046 std::optional<int32_t> foundDeviceId;
5047 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005048 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005049 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005050 foundDeviceId = state.deviceId;
5051 }
5052 }
5053 if (!foundDeviceId || !state.down) {
5054 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005055 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005056 return BAD_VALUE;
5057 }
5058 int32_t deviceId = foundDeviceId.value();
5059
5060 // Send cancel events to all the input channels we're stealing from.
5061 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005062 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005063 options.deviceId = deviceId;
5064 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005065 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005066 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005067 std::shared_ptr<InputChannel> channel =
5068 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005069 if (channel != nullptr) {
5070 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005071 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005072 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005073 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005074 canceledWindows += "]";
5075 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5076 canceledWindows.c_str());
5077
Michael Wright3dd60e22019-03-27 22:06:44 +00005078 // Then clear the current touch state so we stop dispatching to them as well.
5079 state.filterNonMonitors();
5080 }
5081 return OK;
5082}
5083
Prabir Pradhan99987712020-11-10 18:43:05 -08005084void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5085 { // acquire lock
5086 std::scoped_lock _l(mLock);
5087 if (DEBUG_FOCUS) {
5088 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5089 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5090 windowHandle != nullptr ? windowHandle->getName().c_str()
5091 : "token without window");
5092 }
5093
Vishnu Nairc519ff72021-01-21 08:23:08 -08005094 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005095 if (focusedToken != windowToken) {
5096 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5097 enabled ? "enable" : "disable");
5098 return;
5099 }
5100
5101 if (enabled == mFocusedWindowRequestedPointerCapture) {
5102 ALOGW("Ignoring request to %s Pointer Capture: "
5103 "window has %s requested pointer capture.",
5104 enabled ? "enable" : "disable", enabled ? "already" : "not");
5105 return;
5106 }
5107
5108 mFocusedWindowRequestedPointerCapture = enabled;
5109 setPointerCaptureLocked(enabled);
5110 } // release lock
5111
5112 // Wake the thread to process command entries.
5113 mLooper->wake();
5114}
5115
Michael Wright3dd60e22019-03-27 22:06:44 +00005116std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5117 const sp<IBinder>& token) {
5118 for (const auto& it : mGestureMonitorsByDisplay) {
5119 const std::vector<Monitor>& monitors = it.second;
5120 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005121 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005122 return it.first;
5123 }
5124 }
5125 }
5126 return std::nullopt;
5127}
5128
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005129std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5130 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5131 if (gesturePid.has_value()) {
5132 return gesturePid;
5133 }
5134 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5135}
5136
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005137sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005138 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005139 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005140 }
5141
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005142 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005143 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005144 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005145 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
5147 }
Robert Carr4e670e52018-08-15 13:26:12 -07005148
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005149 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150}
5151
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005152std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5153 sp<Connection> connection = getConnectionLocked(connectionToken);
5154 if (connection == nullptr) {
5155 return "<nullptr>";
5156 }
5157 return connection->getInputChannelName();
5158}
5159
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005160void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005161 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005162 removeByValue(mConnectionsByFd, connection);
5163}
5164
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005165void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5166 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005167 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005168 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5169 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 commandEntry->connection = connection;
5171 commandEntry->eventTime = currentTime;
5172 commandEntry->seq = seq;
5173 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005174 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005175 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176}
5177
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005178void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5179 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005181 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005183 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5184 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005186 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187}
5188
Vishnu Nairad321cd2020-08-20 16:40:21 -07005189void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5190 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005191 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5192 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005193 commandEntry->oldToken = oldToken;
5194 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005195 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005196}
5197
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005198void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5199 if (connection == nullptr) {
5200 LOG_ALWAYS_FATAL("Caller must check for nullness");
5201 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5203 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005204 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005205 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005206 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005207 return;
5208 }
5209 /**
5210 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5211 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5212 * has changed. This could cause newer entries to time out before the already dispatched
5213 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5214 * processes the events linearly. So providing information about the oldest entry seems to be
5215 * most useful.
5216 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005217 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005218 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5219 std::string reason =
5220 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005221 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005222 ns2ms(currentWait),
5223 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005224 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005225 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005226
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005227 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5228
5229 // Stop waking up for events on this connection, it is already unresponsive
5230 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005231}
5232
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005233void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5234 std::string reason =
5235 StringPrintf("%s does not have a focused window", application->getName().c_str());
5236 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005237
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005238 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5239 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5240 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005241 postCommandLocked(std::move(commandEntry));
5242}
5243
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005244void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5245 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5246 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5247 commandEntry->obscuringPackage = obscuringPackage;
5248 postCommandLocked(std::move(commandEntry));
5249}
5250
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005251void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5252 const std::string& reason) {
5253 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5254 updateLastAnrStateLocked(windowLabel, reason);
5255}
5256
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005257void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5258 const std::string& reason) {
5259 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005260 updateLastAnrStateLocked(windowLabel, reason);
5261}
5262
5263void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5264 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005266 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 struct tm tm;
5268 localtime_r(&t, &tm);
5269 char timestr[64];
5270 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005271 mLastAnrState.clear();
5272 mLastAnrState += INDENT "ANR:\n";
5273 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005274 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5275 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005276 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277}
5278
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005279void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 mLock.unlock();
5281
5282 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5283
5284 mLock.lock();
5285}
5286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005287void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 sp<Connection> connection = commandEntry->connection;
5289
5290 if (connection->status != Connection::STATUS_ZOMBIE) {
5291 mLock.unlock();
5292
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005293 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294
5295 mLock.lock();
5296 }
5297}
5298
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005299void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005300 sp<IBinder> oldToken = commandEntry->oldToken;
5301 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005302 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005303 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005304 mLock.lock();
5305}
5306
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005307void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005309
5310 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5311
5312 mLock.lock();
5313}
5314
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005315void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005316 mLock.unlock();
5317
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005318 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319
5320 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005321}
5322
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005323void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005324 mLock.unlock();
5325
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005326 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5327
5328 mLock.lock();
5329}
5330
5331void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5332 mLock.unlock();
5333
5334 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5335
5336 mLock.lock();
5337}
5338
5339void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5340 mLock.unlock();
5341
5342 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005343
5344 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005345}
5346
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005347void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5348 mLock.unlock();
5349
5350 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5351
5352 mLock.lock();
5353}
5354
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5356 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005357 KeyEntry& entry = *(commandEntry->keyEntry);
5358 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359
5360 mLock.unlock();
5361
Michael Wright2b3c3302018-03-02 17:19:13 +00005362 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005363 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005364 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005365 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5366 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005367 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369
5370 mLock.lock();
5371
5372 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005373 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005375 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005377 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5378 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380}
5381
chaviwfd6d3512019-03-25 13:23:49 -07005382void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5383 mLock.unlock();
5384 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5385 mLock.lock();
5386}
5387
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005388/**
5389 * Connection is responsive if it has no events in the waitQueue that are older than the
5390 * current time.
5391 */
5392static bool isConnectionResponsive(const Connection& connection) {
5393 const nsecs_t currentTime = now();
5394 for (const DispatchEntry* entry : connection.waitQueue) {
5395 if (entry->timeoutTime < currentTime) {
5396 return false;
5397 }
5398 }
5399 return true;
5400}
5401
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005402void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005404 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005406 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407
5408 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005409 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005410 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005411 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005413 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005414 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005415 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005416 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5417 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005418 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005419 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005420
5421 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005422 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005423 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005424 restartEvent =
5425 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005426 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005427 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005428 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5429 handled);
5430 } else {
5431 restartEvent = false;
5432 }
5433
5434 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005435 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005436 // contents of the wait queue to have been drained, so we need to double-check
5437 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005438 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5439 if (dispatchEntryIt != connection->waitQueue.end()) {
5440 dispatchEntry = *dispatchEntryIt;
5441 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005442 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5443 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005444 if (!connection->responsive) {
5445 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005446 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005447 // The connection was unresponsive, and now it's responsive.
5448 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005449 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005450 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005451 traceWaitQueueLength(connection);
5452 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005453 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005454 traceOutboundQueueLength(connection);
5455 } else {
5456 releaseDispatchEntry(dispatchEntry);
5457 }
5458 }
5459
5460 // Start the next dispatch cycle for this connection.
5461 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462}
5463
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005464void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5465 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5466 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5467 monitorUnresponsiveCommand->pid = pid;
5468 monitorUnresponsiveCommand->reason = std::move(reason);
5469 postCommandLocked(std::move(monitorUnresponsiveCommand));
5470}
5471
5472void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5473 std::string reason) {
5474 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5475 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5476 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5477 windowUnresponsiveCommand->reason = std::move(reason);
5478 postCommandLocked(std::move(windowUnresponsiveCommand));
5479}
5480
5481void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5482 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5483 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5484 monitorResponsiveCommand->pid = pid;
5485 postCommandLocked(std::move(monitorResponsiveCommand));
5486}
5487
5488void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5489 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5490 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5491 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5492 postCommandLocked(std::move(windowResponsiveCommand));
5493}
5494
5495/**
5496 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5497 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5498 * command entry to the command queue.
5499 */
5500void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5501 std::string reason) {
5502 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5503 if (connection.monitor) {
5504 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5505 reason.c_str());
5506 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5507 if (!pid.has_value()) {
5508 ALOGE("Could not find unresponsive monitor for connection %s",
5509 connection.inputChannel->getName().c_str());
5510 return;
5511 }
5512 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5513 return;
5514 }
5515 // If not a monitor, must be a window
5516 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5517 reason.c_str());
5518 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5519}
5520
5521/**
5522 * Tell the policy that a connection has become responsive so that it can stop ANR.
5523 */
5524void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5525 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5526 if (connection.monitor) {
5527 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5528 if (!pid.has_value()) {
5529 ALOGE("Could not find responsive monitor for connection %s",
5530 connection.inputChannel->getName().c_str());
5531 return;
5532 }
5533 sendMonitorResponsiveCommandLocked(pid.value());
5534 return;
5535 }
5536 // If not a monitor, must be a window
5537 sendWindowResponsiveCommandLocked(connectionToken);
5538}
5539
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005541 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005542 KeyEntry& keyEntry, bool handled) {
5543 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005544 if (!handled) {
5545 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005546 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005547 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005548 return false;
5549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005551 // Get the fallback key state.
5552 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005553 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005554 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005555 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005556 connection->inputState.removeFallbackKey(originalKeyCode);
5557 }
5558
5559 if (handled || !dispatchEntry->hasForegroundTarget()) {
5560 // If the application handles the original key for which we previously
5561 // generated a fallback or if the window is not a foreground window,
5562 // then cancel the associated fallback key, if any.
5563 if (fallbackKeyCode != -1) {
5564 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005566 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005567 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005568 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005570 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005571 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572
5573 mLock.unlock();
5574
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005575 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005576 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577
5578 mLock.lock();
5579
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005580 // Cancel the fallback key.
5581 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005583 "application handled the original non-fallback key "
5584 "or is no longer a foreground target, "
5585 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 options.keyCode = fallbackKeyCode;
5587 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005588 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005589 connection->inputState.removeFallbackKey(originalKeyCode);
5590 }
5591 } else {
5592 // If the application did not handle a non-fallback key, first check
5593 // that we are in a good state to perform unhandled key event processing
5594 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005595 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005596 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005598 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005599 "since this is not an initial down. "
5600 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005601 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005603 return false;
5604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005606 // Dispatch the unhandled key to the policy.
5607#if DEBUG_OUTBOUND_EVENT_DETAILS
5608 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005609 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005610 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005611#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005612 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005613
5614 mLock.unlock();
5615
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005616 bool fallback =
5617 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005618 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005619
5620 mLock.lock();
5621
5622 if (connection->status != Connection::STATUS_NORMAL) {
5623 connection->inputState.removeFallbackKey(originalKeyCode);
5624 return false;
5625 }
5626
5627 // Latch the fallback keycode for this key on an initial down.
5628 // The fallback keycode cannot change at any other point in the lifecycle.
5629 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005631 fallbackKeyCode = event.getKeyCode();
5632 } else {
5633 fallbackKeyCode = AKEYCODE_UNKNOWN;
5634 }
5635 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5636 }
5637
5638 ALOG_ASSERT(fallbackKeyCode != -1);
5639
5640 // Cancel the fallback key if the policy decides not to send it anymore.
5641 // We will continue to dispatch the key to the policy but we will no
5642 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005643 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5644 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005645#if DEBUG_OUTBOUND_EVENT_DETAILS
5646 if (fallback) {
5647 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005648 "as a fallback for %d, but on the DOWN it had requested "
5649 "to send %d instead. Fallback canceled.",
5650 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005651 } else {
5652 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005653 "but on the DOWN it had requested to send %d. "
5654 "Fallback canceled.",
5655 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005656 }
5657#endif
5658
5659 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5660 "canceling fallback, policy no longer desires it");
5661 options.keyCode = fallbackKeyCode;
5662 synthesizeCancelationEventsForConnectionLocked(connection, options);
5663
5664 fallback = false;
5665 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005666 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005667 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005668 }
5669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670
5671#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005672 {
5673 std::string msg;
5674 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5675 connection->inputState.getFallbackKeys();
5676 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005677 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005679 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005680 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005681 }
5682#endif
5683
5684 if (fallback) {
5685 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005686 keyEntry.eventTime = event.getEventTime();
5687 keyEntry.deviceId = event.getDeviceId();
5688 keyEntry.source = event.getSource();
5689 keyEntry.displayId = event.getDisplayId();
5690 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5691 keyEntry.keyCode = fallbackKeyCode;
5692 keyEntry.scanCode = event.getScanCode();
5693 keyEntry.metaState = event.getMetaState();
5694 keyEntry.repeatCount = event.getRepeatCount();
5695 keyEntry.downTime = event.getDownTime();
5696 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005697
5698#if DEBUG_OUTBOUND_EVENT_DETAILS
5699 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005700 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005701 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005702#endif
5703 return true; // restart the event
5704 } else {
5705#if DEBUG_OUTBOUND_EVENT_DETAILS
5706 ALOGD("Unhandled key event: No fallback key.");
5707#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005708
5709 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005710 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 }
5712 }
5713 return false;
5714}
5715
5716bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005717 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005718 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719 return false;
5720}
5721
5722void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5723 mLock.unlock();
5724
Sean Stoutb4e0a592021-02-23 07:34:53 -08005725 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
5726 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727
5728 mLock.lock();
5729}
5730
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005731void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5732 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 // TODO Write some statistics about how long we spend waiting.
5734}
5735
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005736/**
5737 * Report the touch event latency to the statsd server.
5738 * Input events are reported for statistics if:
5739 * - This is a touchscreen event
5740 * - InputFilter is not enabled
5741 * - Event is not injected or synthesized
5742 *
5743 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5744 * from getting aggregated with the "old" data.
5745 */
5746void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5747 REQUIRES(mLock) {
5748 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5749 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5750 if (!reportForStatistics) {
5751 return;
5752 }
5753
5754 if (mTouchStatistics.shouldReport()) {
5755 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5756 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5757 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5758 mTouchStatistics.reset();
5759 }
5760 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5761 mTouchStatistics.addValue(latencyMicros);
5762}
5763
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764void InputDispatcher::traceInboundQueueLengthLocked() {
5765 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005766 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 }
5768}
5769
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005770void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 if (ATRACE_ENABLED()) {
5772 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005773 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005774 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 }
5776}
5777
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005778void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 if (ATRACE_ENABLED()) {
5780 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005781 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005782 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784}
5785
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005787 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005789 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 dumpDispatchStateLocked(dump);
5791
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005792 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005793 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005794 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796}
5797
5798void InputDispatcher::monitor() {
5799 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005800 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005802 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803}
5804
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005805/**
5806 * Wake up the dispatcher and wait until it processes all events and commands.
5807 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5808 * this method can be safely called from any thread, as long as you've ensured that
5809 * the work you are interested in completing has already been queued.
5810 */
5811bool InputDispatcher::waitForIdle() {
5812 /**
5813 * Timeout should represent the longest possible time that a device might spend processing
5814 * events and commands.
5815 */
5816 constexpr std::chrono::duration TIMEOUT = 100ms;
5817 std::unique_lock lock(mLock);
5818 mLooper->wake();
5819 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5820 return result == std::cv_status::no_timeout;
5821}
5822
Vishnu Naire798b472020-07-23 13:52:21 -07005823/**
5824 * Sets focus to the window identified by the token. This must be called
5825 * after updating any input window handles.
5826 *
5827 * Params:
5828 * request.token - input channel token used to identify the window that should gain focus.
5829 * request.focusedToken - the token that the caller expects currently to be focused. If the
5830 * specified token does not match the currently focused window, this request will be dropped.
5831 * If the specified focused token matches the currently focused window, the call will succeed.
5832 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5833 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5834 * when requesting the focus change. This determines which request gets
5835 * precedence if there is a focus change request from another source such as pointer down.
5836 */
Vishnu Nair958da932020-08-21 17:12:37 -07005837void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5838 { // acquire lock
5839 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005840 std::optional<FocusResolver::FocusChanges> changes =
5841 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
5842 if (changes) {
5843 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07005844 }
5845 } // release lock
5846 // Wake up poll loop since it may need to make new input dispatching choices.
5847 mLooper->wake();
5848}
5849
Vishnu Nairc519ff72021-01-21 08:23:08 -08005850void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
5851 if (changes.oldFocus) {
5852 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005853 if (focusedInputChannel) {
5854 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5855 "focus left window");
5856 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005857 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005858 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005859 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08005860 if (changes.newFocus) {
5861 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005862 }
5863
Prabir Pradhan99987712020-11-10 18:43:05 -08005864 // If a window has pointer capture, then it must have focus. We need to ensure that this
5865 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5866 // If the window loses focus before it loses pointer capture, then the window can be in a state
5867 // where it has pointer capture but not focus, violating the contract. Therefore we must
5868 // dispatch the pointer capture event before the focus event. Since focus events are added to
5869 // the front of the queue (above), we add the pointer capture event to the front of the queue
5870 // after the focus events are added. This ensures the pointer capture event ends up at the
5871 // front.
5872 disablePointerCaptureForcedLocked();
5873
Vishnu Nairc519ff72021-01-21 08:23:08 -08005874 if (mFocusedDisplayId == changes.displayId) {
5875 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005876 }
5877}
Vishnu Nair958da932020-08-21 17:12:37 -07005878
Prabir Pradhan99987712020-11-10 18:43:05 -08005879void InputDispatcher::disablePointerCaptureForcedLocked() {
5880 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5881 return;
5882 }
5883
5884 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5885
5886 if (mFocusedWindowRequestedPointerCapture) {
5887 mFocusedWindowRequestedPointerCapture = false;
5888 setPointerCaptureLocked(false);
5889 }
5890
5891 if (!mWindowTokenWithPointerCapture) {
5892 // No need to send capture changes because no window has capture.
5893 return;
5894 }
5895
5896 if (mPendingEvent != nullptr) {
5897 // Move the pending event to the front of the queue. This will give the chance
5898 // for the pending event to be dropped if it is a captured event.
5899 mInboundQueue.push_front(mPendingEvent);
5900 mPendingEvent = nullptr;
5901 }
5902
5903 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5904 false /* hasCapture */);
5905 mInboundQueue.push_front(std::move(entry));
5906}
5907
Prabir Pradhan99987712020-11-10 18:43:05 -08005908void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5909 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5910 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5911 commandEntry->enabled = enabled;
5912 postCommandLocked(std::move(commandEntry));
5913}
5914
5915void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5916 android::inputdispatcher::CommandEntry* commandEntry) {
5917 mLock.unlock();
5918
5919 mPolicy->setPointerCapture(commandEntry->enabled);
5920
5921 mLock.lock();
5922}
5923
Garfield Tane84e6f92019-08-29 17:28:41 -07005924} // namespace android::inputdispatcher