blob: 16cb7d7a51d38e8c71d80c75e5e1afecae010859 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080052#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050053#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070054#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100055#include <binder/IServiceManager.h>
56#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080057#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <statslog.h>
63#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wright44753b12020-07-08 13:48:11 +010066#include <cerrno>
67#include <cinttypes>
68#include <climits>
69#include <cstddef>
70#include <ctime>
71#include <queue>
72#include <sstream>
73
74#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070075#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010076
Michael Wrightd02c5b62014-02-10 15:10:22 -080077#define INDENT " "
78#define INDENT2 " "
79#define INDENT3 " "
80#define INDENT4 " "
81
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000083using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080084using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080085using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080087using android::os::InputEventInjectionResult;
88using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100089using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080090
Garfield Tane84e6f92019-08-29 17:28:41 -070091namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// Default input dispatching timeout if there is no focused application or paused window
94// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080095const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
96 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
97 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
99// Amount of time to allow for all pending events to be processed when an app switch
100// key is on the way. This is used to preempt input dispatch and drop input events
101// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Amount of time to allow for an event to be dispatched (measured since its eventTime)
105// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
110
111// Log a warning when an interception call takes longer than this to process.
112constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700114// Additional key latency in case a connection is still processing some motion events.
115// This will help with the case when a user touched a button that opens a new window,
116// and gives us the chance to dispatch the key to this new window.
117constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
118
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000120constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
121
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000122// Event log tags. See EventLogTags.logtags for reference
123constexpr int LOGTAG_INPUT_INTERACTION = 62000;
124constexpr int LOGTAG_INPUT_FOCUS = 62001;
125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126static inline nsecs_t now() {
127 return systemTime(SYSTEM_TIME_MONOTONIC);
128}
129
130static inline const char* toString(bool value) {
131 return value ? "true" : "false";
132}
133
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000134static inline const std::string toString(sp<IBinder> binder) {
135 if (binder == nullptr) {
136 return "<null>";
137 }
138 return StringPrintf("%p", binder.get());
139}
140
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
143 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144}
145
146static bool isValidKeyAction(int32_t action) {
147 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700148 case AKEY_EVENT_ACTION_DOWN:
149 case AKEY_EVENT_ACTION_UP:
150 return true;
151 default:
152 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153 }
154}
155
156static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800158 ALOGE("Key event has invalid action code 0x%x", action);
159 return false;
160 }
161 return true;
162}
163
Michael Wright7b159c92015-05-14 14:48:03 +0100164static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_DOWN:
167 case AMOTION_EVENT_ACTION_UP:
168 case AMOTION_EVENT_ACTION_CANCEL:
169 case AMOTION_EVENT_ACTION_MOVE:
170 case AMOTION_EVENT_ACTION_OUTSIDE:
171 case AMOTION_EVENT_ACTION_HOVER_ENTER:
172 case AMOTION_EVENT_ACTION_HOVER_MOVE:
173 case AMOTION_EVENT_ACTION_HOVER_EXIT:
174 case AMOTION_EVENT_ACTION_SCROLL:
175 return true;
176 case AMOTION_EVENT_ACTION_POINTER_DOWN:
177 case AMOTION_EVENT_ACTION_POINTER_UP: {
178 int32_t index = getMotionEventActionPointerIndex(action);
179 return index >= 0 && index < pointerCount;
180 }
181 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
182 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
183 return actionButton != 0;
184 default:
185 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 }
187}
188
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500189static int64_t millis(std::chrono::nanoseconds t) {
190 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
191}
192
Michael Wright7b159c92015-05-14 14:48:03 +0100193static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 const PointerProperties* pointerProperties) {
195 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 ALOGE("Motion event has invalid action code 0x%x", action);
197 return false;
198 }
199 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000200 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700201 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 return false;
203 }
204 BitSet32 pointerIdBits;
205 for (size_t i = 0; i < pointerCount; i++) {
206 int32_t id = pointerProperties[i].id;
207 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700208 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
209 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 return false;
211 }
212 if (pointerIdBits.hasBit(id)) {
213 ALOGE("Motion event has duplicate pointer id %d", id);
214 return false;
215 }
216 pointerIdBits.markBit(id);
217 }
218 return true;
219}
220
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000221static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000223 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
225
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000226 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 bool first = true;
228 Region::const_iterator cur = region.begin();
229 Region::const_iterator const tail = region.end();
230 while (cur != tail) {
231 if (first) {
232 first = false;
233 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800236 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 cur++;
238 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000239 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240}
241
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500242static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
243 constexpr size_t maxEntries = 50; // max events to print
244 constexpr size_t skipBegin = maxEntries / 2;
245 const size_t skipEnd = queue.size() - maxEntries / 2;
246 // skip from maxEntries / 2 ... size() - maxEntries/2
247 // only print from 0 .. skipBegin and then from skipEnd .. size()
248
249 std::string dump;
250 for (size_t i = 0; i < queue.size(); i++) {
251 const DispatchEntry& entry = *queue[i];
252 if (i >= skipBegin && i < skipEnd) {
253 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
254 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
255 continue;
256 }
257 dump.append(INDENT4);
258 dump += entry.eventEntry->getDescription();
259 dump += StringPrintf(", seq=%" PRIu32
260 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
261 entry.seq, entry.targetFlags, entry.resolvedAction,
262 ns2ms(currentTime - entry.eventEntry->eventTime));
263 if (entry.deliveryTime != 0) {
264 // This entry was delivered, so add information on how long we've been waiting
265 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
266 }
267 dump.append("\n");
268 }
269 return dump;
270}
271
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700272/**
273 * Find the entry in std::unordered_map by key, and return it.
274 * If the entry is not found, return a default constructed entry.
275 *
276 * Useful when the entries are vectors, since an empty vector will be returned
277 * if the entry is not found.
278 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
279 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700280template <typename K, typename V>
281static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700282 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700283 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800284}
285
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,
Evan Rosky84f07f02021-04-16 10:42:42 -0700342 1.0f /*globalScaleFactor*/,
343 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900344 }
345 }
346
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 if (inputTarget.useDefaultPointerTransform()) {
348 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700349 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700350 inputTarget.globalScaleFactor,
351 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 }
353
354 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
355 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
356
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700357 std::vector<PointerCoords> pointerCoords;
358 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 // Use the first pointer information to normalize all other pointers. This could be any pointer
361 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700362 // uses the transform for the normalized pointer.
363 const ui::Transform& firstPointerTransform =
364 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
365 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366
367 // Iterate through all pointers in the event to normalize against the first.
368 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
369 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
370 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700374 // First, apply the current pointer's transform to update the coordinates into
375 // window space.
376 pointerCoords[pointerIndex].transform(currTransform);
377 // Next, apply the inverse transform of the normalized coordinates so the
378 // current coordinates are transformed into the normalized coordinate space.
379 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380 }
381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700382 std::unique_ptr<MotionEntry> combinedMotionEntry =
383 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
384 motionEntry.deviceId, motionEntry.source,
385 motionEntry.displayId, motionEntry.policyFlags,
386 motionEntry.action, motionEntry.actionButton,
387 motionEntry.flags, motionEntry.metaState,
388 motionEntry.buttonState, motionEntry.classification,
389 motionEntry.edgeFlags, motionEntry.xPrecision,
390 motionEntry.yPrecision, motionEntry.xCursorPosition,
391 motionEntry.yCursorPosition, motionEntry.downTime,
392 motionEntry.pointerCount, motionEntry.pointerProperties,
393 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000394
395 if (motionEntry.injectionState) {
396 combinedMotionEntry->injectionState = motionEntry.injectionState;
397 combinedMotionEntry->injectionState->refCount += 1;
398 }
399
400 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700401 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700402 firstPointerTransform, inputTarget.globalScaleFactor,
403 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404 return dispatchEntry;
405}
406
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700407static void addGestureMonitors(const std::vector<Monitor>& monitors,
408 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
409 float yOffset = 0) {
410 if (monitors.empty()) {
411 return;
412 }
413 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
414 for (const Monitor& monitor : monitors) {
415 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
416 }
417}
418
Garfield Tan15601662020-09-22 15:32:38 -0700419static status_t openInputChannelPair(const std::string& name,
420 std::shared_ptr<InputChannel>& serverChannel,
421 std::unique_ptr<InputChannel>& clientChannel) {
422 std::unique_ptr<InputChannel> uniqueServerChannel;
423 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
424
425 serverChannel = std::move(uniqueServerChannel);
426 return result;
427}
428
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500429template <typename T>
430static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
431 if (lhs == nullptr && rhs == nullptr) {
432 return true;
433 }
434 if (lhs == nullptr || rhs == nullptr) {
435 return false;
436 }
437 return *lhs == *rhs;
438}
439
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000440static sp<IPlatformCompatNative> getCompatService() {
441 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
442 if (service == nullptr) {
443 ALOGE("Failed to link to compat service");
444 return nullptr;
445 }
446 return interface_cast<IPlatformCompatNative>(service);
447}
448
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000449static KeyEvent createKeyEvent(const KeyEntry& entry) {
450 KeyEvent event;
451 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
452 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
453 entry.repeatCount, entry.downTime, entry.eventTime);
454 return event;
455}
456
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000457static std::optional<int32_t> findMonitorPidByToken(
458 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
459 const sp<IBinder>& token) {
460 for (const auto& it : monitorsByDisplay) {
461 const std::vector<Monitor>& monitors = it.second;
462 for (const Monitor& monitor : monitors) {
463 if (monitor.inputChannel->getConnectionToken() == token) {
464 return monitor.pid;
465 }
466 }
467 }
468 return std::nullopt;
469}
470
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471// --- InputDispatcher ---
472
Garfield Tan00f511d2019-06-12 16:55:40 -0700473InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
474 : mPolicy(policy),
475 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700476 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800477 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700478 mAppSwitchSawKeyDown(false),
479 mAppSwitchDueTime(LONG_LONG_MAX),
480 mNextUnblockedEvent(nullptr),
481 mDispatchEnabled(false),
482 mDispatchFrozen(false),
483 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800484 // mInTouchMode will be initialized by the WindowManager to the default device config.
485 // To avoid leaking stack in case that call never comes, and for tests,
486 // initialize it here anyways.
487 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100488 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000489 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800490 mFocusedWindowRequestedPointerCapture(false),
491 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000492 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800494 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800495
Yi Kong9b14ac62018-07-17 13:48:38 -0700496 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497
498 policy->getDispatcherConfiguration(&mConfig);
499}
500
501InputDispatcher::~InputDispatcher() {
502 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800503 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504
505 resetKeyRepeatLocked();
506 releasePendingEventLocked();
507 drainInboundQueueLocked();
508 }
509
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700510 while (!mConnectionsByFd.empty()) {
511 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700512 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 }
514}
515
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700516status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700517 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700518 return ALREADY_EXISTS;
519 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700520 mThread = std::make_unique<InputThread>(
521 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
522 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700523}
524
525status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700526 if (mThread && mThread->isCallingThread()) {
527 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700528 return INVALID_OPERATION;
529 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700530 mThread.reset();
531 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700532}
533
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534void InputDispatcher::dispatchOnce() {
535 nsecs_t nextWakeupTime = LONG_LONG_MAX;
536 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800537 std::scoped_lock _l(mLock);
538 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539
540 // Run a dispatch loop if there are no pending commands.
541 // The dispatch loop might enqueue commands to run afterwards.
542 if (!haveCommandsLocked()) {
543 dispatchOnceInnerLocked(&nextWakeupTime);
544 }
545
546 // Run all pending commands if there are any.
547 // If any commands were run then force the next poll to wake up immediately.
548 if (runCommandsLockedInterruptible()) {
549 nextWakeupTime = LONG_LONG_MIN;
550 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800551
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700552 // If we are still waiting for ack on some events,
553 // we might have to wake up earlier to check if an app is anr'ing.
554 const nsecs_t nextAnrCheck = processAnrsLocked();
555 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
556
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800557 // We are about to enter an infinitely long sleep, because we have no commands or
558 // pending or queued events
559 if (nextWakeupTime == LONG_LONG_MAX) {
560 mDispatcherEnteredIdle.notify_all();
561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 } // release lock
563
564 // Wait for callback or timeout or wake. (make sure we round up, not down)
565 nsecs_t currentTime = now();
566 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
567 mLooper->pollOnce(timeoutMillis);
568}
569
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700570/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500571 * Raise ANR if there is no focused window.
572 * Before the ANR is raised, do a final state check:
573 * 1. The currently focused application must be the same one we are waiting for.
574 * 2. Ensure we still don't have a focused window.
575 */
576void InputDispatcher::processNoFocusedWindowAnrLocked() {
577 // Check if the application that we are waiting for is still focused.
578 std::shared_ptr<InputApplicationHandle> focusedApplication =
579 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
580 if (focusedApplication == nullptr ||
581 focusedApplication->getApplicationToken() !=
582 mAwaitedFocusedApplication->getApplicationToken()) {
583 // Unexpected because we should have reset the ANR timer when focused application changed
584 ALOGE("Waited for a focused window, but focused application has already changed to %s",
585 focusedApplication->getName().c_str());
586 return; // The focused application has changed.
587 }
588
589 const sp<InputWindowHandle>& focusedWindowHandle =
590 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
591 if (focusedWindowHandle != nullptr) {
592 return; // We now have a focused window. No need for ANR.
593 }
594 onAnrLocked(mAwaitedFocusedApplication);
595}
596
597/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700598 * Check if any of the connections' wait queues have events that are too old.
599 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
600 * Return the time at which we should wake up next.
601 */
602nsecs_t InputDispatcher::processAnrsLocked() {
603 const nsecs_t currentTime = now();
604 nsecs_t nextAnrCheck = LONG_LONG_MAX;
605 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
606 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
607 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500608 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700609 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500610 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700611 return LONG_LONG_MIN;
612 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500613 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700614 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
615 }
616 }
617
618 // Check if any connection ANRs are due
619 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
620 if (currentTime < nextAnrCheck) { // most likely scenario
621 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
622 }
623
624 // If we reached here, we have an unresponsive connection.
625 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
626 if (connection == nullptr) {
627 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
628 return nextAnrCheck;
629 }
630 connection->responsive = false;
631 // Stop waking up for this unresponsive connection
632 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000633 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700634 return LONG_LONG_MIN;
635}
636
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500637std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638 sp<InputWindowHandle> window = getWindowHandleLocked(token);
639 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500640 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700641 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500642 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700643}
644
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
646 nsecs_t currentTime = now();
647
Jeff Browndc5992e2014-04-11 01:27:26 -0700648 // Reset the key repeat timer whenever normal dispatch is suspended while the
649 // device is in a non-interactive state. This is to ensure that we abort a key
650 // repeat if the device is just coming out of sleep.
651 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 resetKeyRepeatLocked();
653 }
654
655 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
656 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100657 if (DEBUG_FOCUS) {
658 ALOGD("Dispatch frozen. Waiting some more.");
659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 return;
661 }
662
663 // Optimize latency of app switches.
664 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
665 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
666 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
667 if (mAppSwitchDueTime < *nextWakeupTime) {
668 *nextWakeupTime = mAppSwitchDueTime;
669 }
670
671 // Ready to start a new event.
672 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700673 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700674 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 if (isAppSwitchDue) {
676 // The inbound queue is empty so the app switch key we were waiting
677 // for will never arrive. Stop waiting for it.
678 resetPendingAppSwitchLocked(false);
679 isAppSwitchDue = false;
680 }
681
682 // Synthesize a key repeat if appropriate.
683 if (mKeyRepeatState.lastKeyEntry) {
684 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
685 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
686 } else {
687 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
688 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
689 }
690 }
691 }
692
693 // Nothing to do if there is no pending event.
694 if (!mPendingEvent) {
695 return;
696 }
697 } else {
698 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700699 mPendingEvent = mInboundQueue.front();
700 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 traceInboundQueueLengthLocked();
702 }
703
704 // Poke user activity for this event.
705 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700706 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 }
709
710 // Now we have an event to dispatch.
711 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700712 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700714 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700716 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700718 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 }
720
721 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700722 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 }
724
725 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700726 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700727 const ConfigurationChangedEntry& typedEntry =
728 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700730 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700731 break;
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700734 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700735 const DeviceResetEntry& typedEntry =
736 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700738 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700739 break;
740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100742 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700743 std::shared_ptr<FocusEntry> typedEntry =
744 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100745 dispatchFocusLocked(currentTime, typedEntry);
746 done = true;
747 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
748 break;
749 }
750
Prabir Pradhan99987712020-11-10 18:43:05 -0800751 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
752 const auto typedEntry =
753 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
754 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
755 done = true;
756 break;
757 }
758
arthurhungb89ccb02020-12-30 16:19:01 +0800759 case EventEntry::Type::DRAG: {
760 std::shared_ptr<DragEntry> typedEntry =
761 std::static_pointer_cast<DragEntry>(mPendingEvent);
762 dispatchDragLocked(currentTime, typedEntry);
763 done = true;
764 break;
765 }
766
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700767 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700768 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700770 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 resetPendingAppSwitchLocked(true);
772 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 } else if (dropReason == DropReason::NOT_DROPPED) {
774 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 }
776 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700777 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
781 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700783 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700784 break;
785 }
786
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700787 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700788 std::shared_ptr<MotionEntry> motionEntry =
789 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
791 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700793 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
797 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700799 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700800 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
Chris Yef59a2f42020-10-16 12:55:26 -0700802
803 case EventEntry::Type::SENSOR: {
804 std::shared_ptr<SensorEntry> sensorEntry =
805 std::static_pointer_cast<SensorEntry>(mPendingEvent);
806 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
807 dropReason = DropReason::APP_SWITCH;
808 }
809 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
810 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
811 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
812 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
813 dropReason = DropReason::STALE;
814 }
815 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
816 done = true;
817 break;
818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 }
820
821 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700822 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700823 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
Michael Wright3a981722015-06-10 15:26:13 +0100825 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826
827 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 }
830}
831
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700832/**
833 * Return true if the events preceding this incoming motion event should be dropped
834 * Return false otherwise (the default behaviour)
835 */
836bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700837 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700838 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700839
840 // Optimize case where the current application is unresponsive and the user
841 // decides to touch a window in a different application.
842 // If the application takes too long to catch up then we drop all events preceding
843 // the touch into the other window.
844 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700845 int32_t displayId = motionEntry.displayId;
846 int32_t x = static_cast<int32_t>(
847 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
848 int32_t y = static_cast<int32_t>(
849 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
850 sp<InputWindowHandle> touchedWindowHandle =
851 findTouchedWindowAtLocked(displayId, x, y, nullptr);
852 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700853 touchedWindowHandle->getApplicationToken() !=
854 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700855 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 ALOGI("Pruning input queue because user touched a different application while waiting "
857 "for %s",
858 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700859 return true;
860 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700861
862 // Alternatively, maybe there's a gesture monitor that could handle this event
863 std::vector<TouchedMonitor> gestureMonitors =
864 findTouchedGestureMonitorsLocked(displayId, {});
865 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
866 sp<Connection> connection =
867 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000868 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700869 // This monitor could take more input. Drop all events preceding this
870 // event, so that gesture monitor could get a chance to receive the stream
871 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
872 "responsive gesture monitor that may handle the event",
873 mAwaitedFocusedApplication->getName().c_str());
874 return true;
875 }
876 }
877 }
878
879 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
880 // yet been processed by some connections, the dispatcher will wait for these motion
881 // events to be processed before dispatching the key event. This is because these motion events
882 // may cause a new window to be launched, which the user might expect to receive focus.
883 // To prevent waiting forever for such events, just send the key to the currently focused window
884 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
885 ALOGD("Received a new pointer down event, stop waiting for events to process and "
886 "just send the pending key event to the focused window.");
887 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700888 }
889 return false;
890}
891
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700893 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700894 mInboundQueue.push_back(std::move(newEntry));
895 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 traceInboundQueueLengthLocked();
897
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700898 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700899 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 // Optimize app switch latency.
901 // If the application takes too long to catch up then we drop all events preceding
902 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700903 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700905 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700907 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700912 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 mAppSwitchSawKeyDown = false;
914 needWake = true;
915 }
916 }
917 }
918 break;
919 }
920
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700921 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700922 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
923 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700924 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100928 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
930 break;
931 }
932 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800933 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700934 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800935 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
936 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700937 // nothing to do
938 break;
939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 }
941
942 return needWake;
943}
944
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700945void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700946 // Do not store sensor event in recent queue to avoid flooding the queue.
947 if (entry->type != EventEntry::Type::SENSOR) {
948 mRecentQueue.push_back(entry);
949 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700950 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700951 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
953}
954
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700956 int32_t y, TouchState* touchState,
957 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800958 bool addPortalWindows,
959 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700960 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
961 LOG_ALWAYS_FATAL(
962 "Must provide a valid touch state if adding portal windows or outside targets");
963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700965 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800966 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +0800967 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +0800968 continue;
969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 const InputWindowInfo* windowInfo = windowHandle->getInfo();
971 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100972 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973
974 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100975 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
976 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
977 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800979 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 if (portalToDisplayId != ADISPLAY_ID_NONE &&
981 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800982 if (addPortalWindows) {
983 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700984 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800985 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700986 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 // Found window.
990 return windowHandle;
991 }
992 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800993
Michael Wright44753b12020-07-08 13:48:11 +0100994 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700995 touchState->addOrUpdateWindow(windowHandle,
996 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
997 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
1001 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001002 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003}
1004
Garfield Tane84e6f92019-08-29 17:28:41 -07001005std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001006 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001007 std::vector<TouchedMonitor> touchedMonitors;
1008
1009 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1010 addGestureMonitors(monitors, touchedMonitors);
1011 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1012 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1013 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001014 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1015 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001016 }
1017 return touchedMonitors;
1018}
1019
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001020void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 const char* reason;
1022 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 reason = "inbound event was dropped because the policy consumed it";
1028 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 case DropReason::DISABLED:
1030 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 ALOGI("Dropped event because input dispatch is disabled.");
1032 }
1033 reason = "inbound event was dropped because input dispatch is disabled";
1034 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036 ALOGI("Dropped event because of pending overdue app switch.");
1037 reason = "inbound event was dropped because of pending overdue app switch";
1038 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001039 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 ALOGI("Dropped event because the current application is not responding and the user "
1041 "has started interacting with a different application.");
1042 reason = "inbound event was dropped because the current application is not responding "
1043 "and the user has started interacting with a different application";
1044 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001045 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001046 ALOGI("Dropped event because it is stale.");
1047 reason = "inbound event was dropped because it is stale";
1048 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001049 case DropReason::NO_POINTER_CAPTURE:
1050 ALOGI("Dropped event because there is no window with Pointer Capture.");
1051 reason = "inbound event was dropped because there is no window with Pointer Capture";
1052 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001053 case DropReason::NOT_DROPPED: {
1054 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001059 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001060 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1062 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001063 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001066 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1067 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1069 synthesizeCancelationEventsForAllConnectionsLocked(options);
1070 } else {
1071 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1072 synthesizeCancelationEventsForAllConnectionsLocked(options);
1073 }
1074 break;
1075 }
Chris Yef59a2f42020-10-16 12:55:26 -07001076 case EventEntry::Type::SENSOR: {
1077 break;
1078 }
arthurhungb89ccb02020-12-30 16:19:01 +08001079 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1080 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001081 break;
1082 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001083 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001084 case EventEntry::Type::CONFIGURATION_CHANGED:
1085 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001086 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001087 break;
1088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 }
1090}
1091
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001092static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1094 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095}
1096
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001097bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1098 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1099 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1100 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101}
1102
1103bool InputDispatcher::isAppSwitchPendingLocked() {
1104 return mAppSwitchDueTime != LONG_LONG_MAX;
1105}
1106
1107void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1108 mAppSwitchDueTime = LONG_LONG_MAX;
1109
1110#if DEBUG_APP_SWITCH
1111 if (handled) {
1112 ALOGD("App switch has arrived.");
1113 } else {
1114 ALOGD("App switch was abandoned.");
1115 }
1116#endif
1117}
1118
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001120 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121}
1122
1123bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001124 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 return false;
1126 }
1127
1128 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001129 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001130 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001132 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133
1134 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001135 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 return true;
1137}
1138
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001139void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1140 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141}
1142
1143void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001144 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001145 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001146 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 releaseInboundEventLocked(entry);
1148 }
1149 traceInboundQueueLengthLocked();
1150}
1151
1152void InputDispatcher::releasePendingEventLocked() {
1153 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001155 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
1157}
1158
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001159void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001161 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162#if DEBUG_DISPATCH_CYCLE
1163 ALOGD("Injected inbound event was dropped.");
1164#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001165 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
1167 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001168 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171}
1172
1173void InputDispatcher::resetKeyRepeatLocked() {
1174 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001175 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
1177}
1178
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001179std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1180 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181
Michael Wright2e732952014-09-24 13:26:59 -07001182 uint32_t policyFlags = entry->policyFlags &
1183 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001185 std::shared_ptr<KeyEntry> newEntry =
1186 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1187 entry->source, entry->displayId, policyFlags, entry->action,
1188 entry->flags, entry->keyCode, entry->scanCode,
1189 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001191 newEntry->syntheticRepeat = true;
1192 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195}
1196
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001197bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201#endif
1202
1203 // Reset key repeating in case a keyboard device was added or removed or something.
1204 resetKeyRepeatLocked();
1205
1206 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001207 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1208 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001210 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 return true;
1212}
1213
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001214bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1215 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1218 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219#endif
1220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 synthesizeCancelationEventsForAllConnectionsLocked(options);
1224 return true;
1225}
1226
Vishnu Nairad321cd2020-08-20 16:40:21 -07001227void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001228 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001229 if (mPendingEvent != nullptr) {
1230 // Move the pending event to the front of the queue. This will give the chance
1231 // for the pending event to get dispatched to the newly focused window
1232 mInboundQueue.push_front(mPendingEvent);
1233 mPendingEvent = nullptr;
1234 }
1235
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236 std::unique_ptr<FocusEntry> focusEntry =
1237 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1238 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001239
1240 // This event should go to the front of the queue, but behind all other focus events
1241 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001243 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244 [](const std::shared_ptr<EventEntry>& event) {
1245 return event->type == EventEntry::Type::FOCUS;
1246 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001247
1248 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001250}
1251
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001253 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001254 if (channel == nullptr) {
1255 return; // Window has gone away
1256 }
1257 InputTarget target;
1258 target.inputChannel = channel;
1259 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1260 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001261 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1262 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001263 std::string reason = std::string("reason=").append(entry->reason);
1264 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001265 dispatchEventLocked(currentTime, entry, {target});
1266}
1267
Prabir Pradhan99987712020-11-10 18:43:05 -08001268void InputDispatcher::dispatchPointerCaptureChangedLocked(
1269 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1270 DropReason& dropReason) {
1271 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001272 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1273 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1274 }
1275 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001276 // Pointer capture was already forcefully disabled because of focus change.
1277 dropReason = DropReason::NOT_DROPPED;
1278 return;
1279 }
1280
1281 // Set drop reason for early returns
1282 dropReason = DropReason::NO_POINTER_CAPTURE;
1283
1284 sp<IBinder> token;
1285 if (entry->pointerCaptureEnabled) {
1286 // Enable Pointer Capture
1287 if (!mFocusedWindowRequestedPointerCapture) {
1288 // This can happen if a window requests capture and immediately releases capture.
1289 ALOGW("No window requested Pointer Capture.");
1290 return;
1291 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001292 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001293 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1294 mWindowTokenWithPointerCapture = token;
1295 } else {
1296 // Disable Pointer Capture
1297 token = mWindowTokenWithPointerCapture;
1298 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001299 if (mFocusedWindowRequestedPointerCapture) {
1300 mFocusedWindowRequestedPointerCapture = false;
1301 setPointerCaptureLocked(false);
1302 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001303 }
1304
1305 auto channel = getInputChannelLocked(token);
1306 if (channel == nullptr) {
1307 // Window has gone away, clean up Pointer Capture state.
1308 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001309 if (mFocusedWindowRequestedPointerCapture) {
1310 mFocusedWindowRequestedPointerCapture = false;
1311 setPointerCaptureLocked(false);
1312 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001313 return;
1314 }
1315 InputTarget target;
1316 target.inputChannel = channel;
1317 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1318 entry->dispatchInProgress = true;
1319 dispatchEventLocked(currentTime, entry, {target});
1320
1321 dropReason = DropReason::NOT_DROPPED;
1322}
1323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001324bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 if (!entry->dispatchInProgress) {
1328 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1329 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1330 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1331 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001332 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 // We have seen two identical key downs in a row which indicates that the device
1334 // driver is automatically generating key repeats itself. We take note of the
1335 // repeat here, but we disable our own next key repeat timer since it is clear that
1336 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001337 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1338 // Make sure we don't get key down from a different device. If a different
1339 // device Id has same key pressed down, the new device Id will replace the
1340 // current one to hold the key repeat with repeat count reset.
1341 // In the future when got a KEY_UP on the device id, drop it and do not
1342 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1344 resetKeyRepeatLocked();
1345 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1346 } else {
1347 // Not a repeat. Save key down state in case we do see a repeat later.
1348 resetKeyRepeatLocked();
1349 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1350 }
1351 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001352 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1353 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001355#if DEBUG_INBOUND_EVENT_DETAILS
1356 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1357#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001358 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 resetKeyRepeatLocked();
1360 }
1361
1362 if (entry->repeatCount == 1) {
1363 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1364 } else {
1365 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1366 }
1367
1368 entry->dispatchInProgress = true;
1369
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001370 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 }
1372
1373 // Handle case where the policy asked us to try again later last time.
1374 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1375 if (currentTime < entry->interceptKeyWakeupTime) {
1376 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1377 *nextWakeupTime = entry->interceptKeyWakeupTime;
1378 }
1379 return false; // wait until next wakeup
1380 }
1381 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1382 entry->interceptKeyWakeupTime = 0;
1383 }
1384
1385 // Give the policy a chance to intercept the key.
1386 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1387 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001388 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001389 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001390 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001391 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001392 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001394 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 return false; // wait for the command to run
1396 } else {
1397 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1398 }
1399 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001400 if (*dropReason == DropReason::NOT_DROPPED) {
1401 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 }
1403 }
1404
1405 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001406 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001407 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001408 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1409 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001410 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 return true;
1412 }
1413
1414 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001415 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001416 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001417 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001418 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 return false;
1420 }
1421
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001422 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001423 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 return true;
1425 }
1426
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001427 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001428 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429
1430 // Dispatch the key.
1431 dispatchEventLocked(currentTime, entry, inputTargets);
1432 return true;
1433}
1434
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001435void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001437 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001438 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1439 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001440 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1441 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1442 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443#endif
1444}
1445
Chris Yef59a2f42020-10-16 12:55:26 -07001446void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1447 mLock.unlock();
1448
1449 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1450 if (entry->accuracyChanged) {
1451 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1452 }
1453 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1454 entry->hwTimestamp, entry->values);
1455 mLock.lock();
1456}
1457
1458void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1459 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1460#if DEBUG_OUTBOUND_EVENT_DETAILS
1461 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1462 "source=0x%x, sensorType=%s",
1463 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001464 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001465#endif
1466 std::unique_ptr<CommandEntry> commandEntry =
1467 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1468 commandEntry->sensorEntry = entry;
1469 postCommandLocked(std::move(commandEntry));
1470}
1471
1472bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1473#if DEBUG_OUTBOUND_EVENT_DETAILS
1474 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1475 NamedEnum::string(sensorType).c_str());
1476#endif
1477 { // acquire lock
1478 std::scoped_lock _l(mLock);
1479
1480 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1481 std::shared_ptr<EventEntry> entry = *it;
1482 if (entry->type == EventEntry::Type::SENSOR) {
1483 it = mInboundQueue.erase(it);
1484 releaseInboundEventLocked(entry);
1485 }
1486 }
1487 }
1488 return true;
1489}
1490
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001491bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001492 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001493 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 entry->dispatchInProgress = true;
1497
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001498 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 }
1500
1501 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001502 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001503 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001504 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1505 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 return true;
1507 }
1508
1509 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1510
1511 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001512 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513
1514 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001515 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 if (isPointerEvent) {
1517 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001518 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001519 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001520 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 } else {
1522 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001523 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001524 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001526 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 return false;
1528 }
1529
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001530 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001531 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001532 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1533 return true;
1534 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001535 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001536 CancelationOptions::Mode mode(isPointerEvent
1537 ? CancelationOptions::CANCEL_POINTER_EVENTS
1538 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1539 CancelationOptions options(mode, "input event injection failed");
1540 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 return true;
1542 }
1543
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001544 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001545 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001547 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001548 std::unordered_map<int32_t, TouchState>::iterator it =
1549 mTouchStatesByDisplay.find(entry->displayId);
1550 if (it != mTouchStatesByDisplay.end()) {
1551 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001552 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001553 // The event has gone through these portal windows, so we add monitoring targets of
1554 // the corresponding displays as well.
1555 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001556 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001557 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001559 }
1560 }
1561 }
1562 }
1563
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 // Dispatch the motion.
1565 if (conflictingPointerActions) {
1566 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001567 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 synthesizeCancelationEventsForAllConnectionsLocked(options);
1569 }
1570 dispatchEventLocked(currentTime, entry, inputTargets);
1571 return true;
1572}
1573
arthurhungb89ccb02020-12-30 16:19:01 +08001574void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1575 bool isExiting, const MotionEntry& motionEntry) {
1576 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1577 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1578 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1579 PointerCoords pointerCoords;
1580 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1581 pointerCoords.transform(windowHandle->getInfo()->transform);
1582
1583 std::unique_ptr<DragEntry> dragEntry =
1584 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1585 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1586 pointerCoords.getY());
1587
1588 enqueueInboundEventLocked(std::move(dragEntry));
1589}
1590
1591void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1592 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1593 if (channel == nullptr) {
1594 return; // Window has gone away
1595 }
1596 InputTarget target;
1597 target.inputChannel = channel;
1598 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1599 entry->dispatchInProgress = true;
1600 dispatchEventLocked(currentTime, entry, {target});
1601}
1602
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001605 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001606 ", policyFlags=0x%x, "
1607 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1608 "metaState=0x%x, buttonState=0x%x,"
1609 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1611 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1612 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001614 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001616 "x=%f, y=%f, pressure=%f, size=%f, "
1617 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1618 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001619 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1620 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1621 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1622 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1623 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1624 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1625 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1626 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1627 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1628 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 }
1630#endif
1631}
1632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001633void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1634 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001635 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001636 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637#if DEBUG_DISPATCH_CYCLE
1638 ALOGD("dispatchEventToCurrentInputTargets");
1639#endif
1640
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001641 updateInteractionTokensLocked(*eventEntry, inputTargets);
1642
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1644
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001645 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001647 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001648 sp<Connection> connection =
1649 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001650 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001651 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001653 if (DEBUG_FOCUS) {
1654 ALOGD("Dropping event delivery to target with channel '%s' because it "
1655 "is no longer registered with the input dispatcher.",
1656 inputTarget.inputChannel->getName().c_str());
1657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 }
1659 }
1660}
1661
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001662void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1663 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1664 // If the policy decides to close the app, we will get a channel removal event via
1665 // unregisterInputChannel, and will clean up the connection that way. We are already not
1666 // sending new pointers to the connection when it blocked, but focused events will continue to
1667 // pile up.
1668 ALOGW("Canceling events for %s because it is unresponsive",
1669 connection->inputChannel->getName().c_str());
1670 if (connection->status == Connection::STATUS_NORMAL) {
1671 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1672 "application not responding");
1673 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 }
1675}
1676
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001677void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001678 if (DEBUG_FOCUS) {
1679 ALOGD("Resetting ANR timeouts.");
1680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681
1682 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001683 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001684 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685}
1686
Tiger Huang721e26f2018-07-24 22:26:19 +08001687/**
1688 * Get the display id that the given event should go to. If this event specifies a valid display id,
1689 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1690 * Focused display is the display that the user most recently interacted with.
1691 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001692int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001693 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001694 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001695 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1697 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001698 break;
1699 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001700 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1702 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001703 break;
1704 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001705 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001706 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001707 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001708 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001709 case EventEntry::Type::SENSOR:
1710 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001711 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 return ADISPLAY_ID_NONE;
1713 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001714 }
1715 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1716}
1717
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001718bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1719 const char* focusedWindowName) {
1720 if (mAnrTracker.empty()) {
1721 // already processed all events that we waited for
1722 mKeyIsWaitingForEventsTimeout = std::nullopt;
1723 return false;
1724 }
1725
1726 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1727 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001728 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001729 mKeyIsWaitingForEventsTimeout = currentTime +
1730 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1731 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001732 return true;
1733 }
1734
1735 // We still have pending events, and already started the timer
1736 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1737 return true; // Still waiting
1738 }
1739
1740 // Waited too long, and some connection still hasn't processed all motions
1741 // Just send the key to the focused window
1742 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1743 focusedWindowName);
1744 mKeyIsWaitingForEventsTimeout = std::nullopt;
1745 return false;
1746}
1747
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001748InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1749 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1750 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001751 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752
Tiger Huang721e26f2018-07-24 22:26:19 +08001753 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001754 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001755 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001756 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1757
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 // If there is no currently focused window and no focused application
1759 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001760 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1761 ALOGI("Dropping %s event because there is no focused window or focused application in "
1762 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001763 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001764 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 }
1766
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001767 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1768 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1769 // start interacting with another application via touch (app switch). This code can be removed
1770 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1771 // an app is expected to have a focused window.
1772 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1773 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1774 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001775 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1776 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1777 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001778 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001779 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001780 ALOGW("Waiting because no window has focus but %s may eventually add a "
1781 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001782 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001783 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001784 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001785 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1786 // Already raised ANR. Drop the event
1787 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001788 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001789 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001790 } else {
1791 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001792 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001793 }
1794 }
1795
1796 // we have a valid, non-null focused window
1797 resetNoFocusedWindowTimeoutLocked();
1798
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001800 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001801 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 }
1803
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001804 if (focusedWindowHandle->getInfo()->paused) {
1805 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001807 }
1808
1809 // If the event is a key event, then we must wait for all previous events to
1810 // complete before delivering it because previous events may have the
1811 // side-effect of transferring focus to a different window and we want to
1812 // ensure that the following keys are sent to the new window.
1813 //
1814 // Suppose the user touches a button in a window then immediately presses "A".
1815 // If the button causes a pop-up window to appear then we want to ensure that
1816 // the "A" key is delivered to the new pop-up window. This is because users
1817 // often anticipate pending UI changes when typing on a keyboard.
1818 // To obtain this behavior, we must serialize key events with respect to all
1819 // prior input events.
1820 if (entry.type == EventEntry::Type::KEY) {
1821 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1822 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001823 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 }
1826
1827 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001828 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001829 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1830 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831
1832 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001833 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834}
1835
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836/**
1837 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1838 * that are currently unresponsive.
1839 */
1840std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1841 const std::vector<TouchedMonitor>& monitors) const {
1842 std::vector<TouchedMonitor> responsiveMonitors;
1843 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1844 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1845 sp<Connection> connection = getConnectionLocked(
1846 monitor.monitor.inputChannel->getConnectionToken());
1847 if (connection == nullptr) {
1848 ALOGE("Could not find connection for monitor %s",
1849 monitor.monitor.inputChannel->getName().c_str());
1850 return false;
1851 }
1852 if (!connection->responsive) {
1853 ALOGW("Unresponsive monitor %s will not get the new gesture",
1854 connection->inputChannel->getName().c_str());
1855 return false;
1856 }
1857 return true;
1858 });
1859 return responsiveMonitors;
1860}
1861
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1863 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1864 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001865 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 enum InjectionPermission {
1867 INJECTION_PERMISSION_UNKNOWN,
1868 INJECTION_PERMISSION_GRANTED,
1869 INJECTION_PERMISSION_DENIED
1870 };
1871
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 // For security reasons, we defer updating the touch state until we are sure that
1873 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001874 int32_t displayId = entry.displayId;
1875 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1877
1878 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001881 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1882 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001884 // Copy current touch state into tempTouchState.
1885 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1886 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001887 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001888 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001889 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1890 mTouchStatesByDisplay.find(displayId);
1891 if (oldStateIt != mTouchStatesByDisplay.end()) {
1892 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001893 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001894 }
1895
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001896 bool isSplit = tempTouchState.split;
1897 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1898 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1899 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001900 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1901 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1902 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1903 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1904 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001905 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 bool wrongDevice = false;
1907 if (newGesture) {
1908 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001909 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001910 ALOGI("Dropping event because a pointer for a different device is already down "
1911 "in display %" PRId32,
1912 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001913 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001914 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 switchedDevice = false;
1916 wrongDevice = true;
1917 goto Failed;
1918 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001919 tempTouchState.reset();
1920 tempTouchState.down = down;
1921 tempTouchState.deviceId = entry.deviceId;
1922 tempTouchState.source = entry.source;
1923 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001925 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001926 ALOGI("Dropping move event because a pointer for a different device is already active "
1927 "in display %" PRId32,
1928 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001929 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001930 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001931 switchedDevice = false;
1932 wrongDevice = true;
1933 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 }
1935
1936 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1937 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1938
Garfield Tan00f511d2019-06-12 16:55:40 -07001939 int32_t x;
1940 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001942 // Always dispatch mouse events to cursor position.
1943 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001944 x = int32_t(entry.xCursorPosition);
1945 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001946 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001947 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1948 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001949 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001950 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001951 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1953 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001954
1955 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001956 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001957 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001960 if (newTouchedWindowHandle != nullptr &&
1961 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001962 // New window supports splitting, but we should never split mouse events.
1963 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 } else if (isSplit) {
1965 // New window does not support splitting but we have already split events.
1966 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001967 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 }
1969
1970 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001971 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001973 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001974 }
1975
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001976 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1977 ALOGI("Not sending touch event to %s because it is paused",
1978 newTouchedWindowHandle->getName().c_str());
1979 newTouchedWindowHandle = nullptr;
1980 }
1981
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001982 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001983 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001984 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1985 if (!isResponsive) {
1986 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1988 newTouchedWindowHandle = nullptr;
1989 }
1990 }
1991
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001992 // Drop events that can't be trusted due to occlusion
1993 if (newTouchedWindowHandle != nullptr &&
1994 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1995 TouchOcclusionInfo occlusionInfo =
1996 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001997 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001998 if (DEBUG_TOUCH_OCCLUSION) {
1999 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2000 for (const auto& log : occlusionInfo.debugInfo) {
2001 ALOGD("%s", log.c_str());
2002 }
2003 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002004 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2005 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2006 ALOGW("Dropping untrusted touch event due to %s/%d",
2007 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2008 newTouchedWindowHandle = nullptr;
2009 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002010 }
2011 }
2012
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002013 // Also don't send the new touch event to unresponsive gesture monitors
2014 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2015
Michael Wright3dd60e22019-03-27 22:06:44 +00002016 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2017 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002018 "(%d, %d) in display %" PRId32 ".",
2019 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002020 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002021 goto Failed;
2022 }
2023
2024 if (newTouchedWindowHandle != nullptr) {
2025 // Set target flags.
2026 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2027 if (isSplit) {
2028 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002030 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2031 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2032 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2033 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2034 }
2035
2036 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002037 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2038 newHoverWindowHandle = nullptr;
2039 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002040 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002041 }
2042
2043 // Update the temporary touch state.
2044 BitSet32 pointerIds;
2045 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002046 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002047 pointerIds.markBit(pointerId);
2048 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002049 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 }
2051
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002052 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 } else {
2054 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2055
2056 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002057 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002058 if (DEBUG_FOCUS) {
2059 ALOGD("Dropping event because the pointer is not down or we previously "
2060 "dropped the pointer down event in display %" PRId32,
2061 displayId);
2062 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002063 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 goto Failed;
2065 }
2066
arthurhung6d4bed92021-03-17 11:59:33 +08002067 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002068
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002070 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002071 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002072 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2073 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074
2075 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002076 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002077 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002078 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2079 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002080 if (DEBUG_FOCUS) {
2081 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2082 oldTouchedWindowHandle->getName().c_str(),
2083 newTouchedWindowHandle->getName().c_str(), displayId);
2084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002086 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2087 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2088 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089
2090 // Make a slippery entrance into the new window.
2091 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2092 isSplit = true;
2093 }
2094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 int32_t targetFlags =
2096 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 if (isSplit) {
2098 targetFlags |= InputTarget::FLAG_SPLIT;
2099 }
2100 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2101 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002102 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2103 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
2105
2106 BitSet32 pointerIds;
2107 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002108 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002110 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 }
2112 }
2113 }
2114
2115 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002116 // Let the previous window know that the hover sequence is over, unless we already did it
2117 // when dispatching it as is to newTouchedWindowHandle.
2118 if (mLastHoverWindowHandle != nullptr &&
2119 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2120 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121#if DEBUG_HOVER
2122 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002123 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002125 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2126 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 }
2128
Garfield Tandf26e862020-07-01 20:18:19 -07002129 // Let the new window know that the hover sequence is starting, unless we already did it
2130 // when dispatching it as is to newTouchedWindowHandle.
2131 if (newHoverWindowHandle != nullptr &&
2132 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2133 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134#if DEBUG_HOVER
2135 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002136 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002138 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2139 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2140 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 }
2142 }
2143
2144 // Check permission to inject into all touched foreground windows and ensure there
2145 // is at least one touched foreground window.
2146 {
2147 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002148 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2150 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002151 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002152 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 injectionPermission = INJECTION_PERMISSION_DENIED;
2154 goto Failed;
2155 }
2156 }
2157 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002158 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002159 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002160 ALOGI("Dropping event because there is no touched foreground window in display "
2161 "%" PRId32 " or gesture monitor to receive it.",
2162 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002163 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 goto Failed;
2165 }
2166
2167 // Permission granted to injection into all touched foreground windows.
2168 injectionPermission = INJECTION_PERMISSION_GRANTED;
2169 }
2170
2171 // Check whether windows listening for outside touches are owned by the same UID. If it is
2172 // set the policy flag that we will not reveal coordinate information to this window.
2173 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2174 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002175 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002176 if (foregroundWindowHandle) {
2177 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2180 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2181 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002182 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2183 InputTarget::FLAG_ZERO_COORDS,
2184 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187 }
2188 }
2189 }
2190
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 // If this is the first pointer going down and the touched window has a wallpaper
2192 // then also add the touched wallpaper windows so they are locked in for the duration
2193 // of the touch gesture.
2194 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2195 // engine only supports touch events. We would need to add a mechanism similar
2196 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2197 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2198 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002199 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002200 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002201 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002202 getWindowHandlesLocked(displayId);
2203 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002205 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002206 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002207 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002208 .addOrUpdateWindow(windowHandle,
2209 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2210 InputTarget::
2211 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2212 InputTarget::FLAG_DISPATCH_AS_IS,
2213 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 }
2215 }
2216 }
2217 }
2218
2219 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002220 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002222 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002224 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002228 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002229 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 }
2231
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 // Drop the outside or hover touch windows since we will not care about them
2233 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002234 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235
2236Failed:
2237 // Check injection permission once and for all.
2238 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002239 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 injectionPermission = INJECTION_PERMISSION_GRANTED;
2241 } else {
2242 injectionPermission = INJECTION_PERMISSION_DENIED;
2243 }
2244 }
2245
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002246 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2247 return injectionResult;
2248 }
2249
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002251 if (!wrongDevice) {
2252 if (switchedDevice) {
2253 if (DEBUG_FOCUS) {
2254 ALOGD("Conflicting pointer actions: Switched to a different device.");
2255 }
2256 *outConflictingPointerActions = true;
2257 }
2258
2259 if (isHoverAction) {
2260 // Started hovering, therefore no longer down.
2261 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002262 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002263 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2264 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 *outConflictingPointerActions = true;
2267 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002268 tempTouchState.reset();
2269 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2270 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2271 tempTouchState.deviceId = entry.deviceId;
2272 tempTouchState.source = entry.source;
2273 tempTouchState.displayId = displayId;
2274 }
2275 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2276 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2277 // All pointers up or canceled.
2278 tempTouchState.reset();
2279 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2280 // First pointer went down.
2281 if (oldState && oldState->down) {
2282 if (DEBUG_FOCUS) {
2283 ALOGD("Conflicting pointer actions: Down received while already down.");
2284 }
2285 *outConflictingPointerActions = true;
2286 }
2287 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2288 // One pointer went up.
2289 if (isSplit) {
2290 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2291 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002293 for (size_t i = 0; i < tempTouchState.windows.size();) {
2294 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2295 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2296 touchedWindow.pointerIds.clearBit(pointerId);
2297 if (touchedWindow.pointerIds.isEmpty()) {
2298 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2299 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002302 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002304 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002305 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002306
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002307 // Save changes unless the action was scroll in which case the temporary touch
2308 // state was only valid for this one action.
2309 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2310 if (tempTouchState.displayId >= 0) {
2311 mTouchStatesByDisplay[displayId] = tempTouchState;
2312 } else {
2313 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002317 // Update hover state.
2318 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 }
2320
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 return injectionResult;
2322}
2323
arthurhung6d4bed92021-03-17 11:59:33 +08002324void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2325 const sp<InputWindowHandle> dropWindow =
2326 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2327 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2328 true /*ignoreDragWindow*/);
2329 if (dropWindow) {
2330 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2331 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002332 } else {
2333 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002334 }
2335 mDragState.reset();
2336}
2337
2338void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2339 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002340 return;
2341 }
2342
arthurhung6d4bed92021-03-17 11:59:33 +08002343 if (!mDragState->isStartDrag) {
2344 mDragState->isStartDrag = true;
2345 mDragState->isStylusButtonDownAtStart =
2346 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2347 }
2348
arthurhungb89ccb02020-12-30 16:19:01 +08002349 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2350 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2351 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2352 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002353 // Handle the special case : stylus button no longer pressed.
2354 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2355 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2356 finishDragAndDrop(entry.displayId, x, y);
2357 return;
2358 }
2359
arthurhungb89ccb02020-12-30 16:19:01 +08002360 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002361 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002362 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2363 true /*ignoreDragWindow*/);
2364 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002365 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2366 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2367 if (mDragState->dragHoverWindowHandle != nullptr) {
2368 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2369 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002370 }
arthurhung6d4bed92021-03-17 11:59:33 +08002371 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002372 }
2373 // enqueue drag location if needed.
2374 if (hoverWindowHandle != nullptr) {
2375 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2376 }
arthurhung6d4bed92021-03-17 11:59:33 +08002377 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2378 finishDragAndDrop(entry.displayId, x, y);
2379 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002380 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002381 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002382 }
2383}
2384
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002386 int32_t targetFlags, BitSet32 pointerIds,
2387 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002388 std::vector<InputTarget>::iterator it =
2389 std::find_if(inputTargets.begin(), inputTargets.end(),
2390 [&windowHandle](const InputTarget& inputTarget) {
2391 return inputTarget.inputChannel->getConnectionToken() ==
2392 windowHandle->getToken();
2393 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002394
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002395 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002396
2397 if (it == inputTargets.end()) {
2398 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002399 std::shared_ptr<InputChannel> inputChannel =
2400 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002401 if (inputChannel == nullptr) {
2402 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2403 return;
2404 }
2405 inputTarget.inputChannel = inputChannel;
2406 inputTarget.flags = targetFlags;
2407 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002408 inputTarget.displaySize =
2409 vec2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002410 inputTargets.push_back(inputTarget);
2411 it = inputTargets.end() - 1;
2412 }
2413
2414 ALOG_ASSERT(it->flags == targetFlags);
2415 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2416
chaviw1ff3d1e2020-07-01 15:53:47 -07002417 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418}
2419
Michael Wright3dd60e22019-03-27 22:06:44 +00002420void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002421 int32_t displayId, float xOffset,
2422 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002423 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2424 mGlobalMonitorsByDisplay.find(displayId);
2425
2426 if (it != mGlobalMonitorsByDisplay.end()) {
2427 const std::vector<Monitor>& monitors = it->second;
2428 for (const Monitor& monitor : monitors) {
2429 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
2432}
2433
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002434void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2435 float yOffset,
2436 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002437 InputTarget target;
2438 target.inputChannel = monitor.inputChannel;
2439 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002440 ui::Transform t;
2441 t.set(xOffset, yOffset);
2442 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002443 inputTargets.push_back(target);
2444}
2445
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002447 const InjectionState* injectionState) {
2448 if (injectionState &&
2449 (windowHandle == nullptr ||
2450 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2451 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002452 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002454 "owned by uid %d",
2455 injectionState->injectorPid, injectionState->injectorUid,
2456 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 } else {
2458 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
2461 return false;
2462 }
2463 return true;
2464}
2465
Robert Carrc9bf1d32020-04-13 17:21:08 -07002466/**
2467 * Indicate whether one window handle should be considered as obscuring
2468 * another window handle. We only check a few preconditions. Actually
2469 * checking the bounds is left to the caller.
2470 */
2471static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2472 const sp<InputWindowHandle>& otherHandle) {
2473 // Compare by token so cloned layers aren't counted
2474 if (haveSameToken(windowHandle, otherHandle)) {
2475 return false;
2476 }
2477 auto info = windowHandle->getInfo();
2478 auto otherInfo = otherHandle->getInfo();
2479 if (!otherInfo->visible) {
2480 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002481 } else if (otherInfo->alpha == 0 &&
2482 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2483 // Those act as if they were invisible, so we don't need to flag them.
2484 // We do want to potentially flag touchable windows even if they have 0
2485 // opacity, since they can consume touches and alter the effects of the
2486 // user interaction (eg. apps that rely on
2487 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2488 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2489 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002490 } else if (info->ownerUid == otherInfo->ownerUid) {
2491 // If ownerUid is the same we don't generate occlusion events as there
2492 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002493 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002494 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002495 return false;
2496 } else if (otherInfo->displayId != info->displayId) {
2497 return false;
2498 }
2499 return true;
2500}
2501
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002502/**
2503 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2504 * untrusted, one should check:
2505 *
2506 * 1. If result.hasBlockingOcclusion is true.
2507 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2508 * BLOCK_UNTRUSTED.
2509 *
2510 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2511 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2512 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2513 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2514 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2515 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2516 *
2517 * If neither of those is true, then it means the touch can be allowed.
2518 */
2519InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2520 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002521 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2522 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002523 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2524 TouchOcclusionInfo info;
2525 info.hasBlockingOcclusion = false;
2526 info.obscuringOpacity = 0;
2527 info.obscuringUid = -1;
2528 std::map<int32_t, float> opacityByUid;
2529 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2530 if (windowHandle == otherHandle) {
2531 break; // All future windows are below us. Exit early.
2532 }
2533 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002534 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2535 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002536 if (DEBUG_TOUCH_OCCLUSION) {
2537 info.debugInfo.push_back(
2538 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2539 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002540 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2541 // we perform the checks below to see if the touch can be propagated or not based on the
2542 // window's touch occlusion mode
2543 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2544 info.hasBlockingOcclusion = true;
2545 info.obscuringUid = otherInfo->ownerUid;
2546 info.obscuringPackage = otherInfo->packageName;
2547 break;
2548 }
2549 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2550 uint32_t uid = otherInfo->ownerUid;
2551 float opacity =
2552 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2553 // Given windows A and B:
2554 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2555 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2556 opacityByUid[uid] = opacity;
2557 if (opacity > info.obscuringOpacity) {
2558 info.obscuringOpacity = opacity;
2559 info.obscuringUid = uid;
2560 info.obscuringPackage = otherInfo->packageName;
2561 }
2562 }
2563 }
2564 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002565 if (DEBUG_TOUCH_OCCLUSION) {
2566 info.debugInfo.push_back(
2567 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2568 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002569 return info;
2570}
2571
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002572std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2573 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002574 return StringPrintf(INDENT2
2575 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2576 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2577 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2578 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002579 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002580 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002581 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002582 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2583 info->frameTop, info->frameRight, info->frameBottom,
2584 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002585 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2586 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2587 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002588}
2589
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002590bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2591 if (occlusionInfo.hasBlockingOcclusion) {
2592 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2593 occlusionInfo.obscuringUid);
2594 return false;
2595 }
2596 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2597 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2598 "%.2f, maximum allowed = %.2f)",
2599 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2600 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2601 return false;
2602 }
2603 return true;
2604}
2605
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2607 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002609 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002610 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002611 if (windowHandle == otherHandle) {
2612 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002615 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002616 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 return true;
2618 }
2619 }
2620 return false;
2621}
2622
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002623bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2624 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002625 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002626 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002627 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002628 if (windowHandle == otherHandle) {
2629 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002630 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002631 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002632 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002633 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002634 return true;
2635 }
2636 }
2637 return false;
2638}
2639
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002640std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002641 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002643 if (applicationHandle != nullptr) {
2644 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002645 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 } else {
2647 return applicationHandle->getName();
2648 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002649 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002650 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002652 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
2654}
2655
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002656void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002657 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002658 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2659 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002660 // Focus or pointer capture changed events are passed to apps, but do not represent user
2661 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002662 return;
2663 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002664 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002665 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002666 if (focusedWindowHandle != nullptr) {
2667 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002668 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002670 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671#endif
2672 return;
2673 }
2674 }
2675
2676 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002677 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002678 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002679 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2680 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002681 return;
2682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002684 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002685 eventType = USER_ACTIVITY_EVENT_TOUCH;
2686 }
2687 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002689 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002690 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2691 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 return;
2693 }
2694 eventType = USER_ACTIVITY_EVENT_BUTTON;
2695 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002697 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002698 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002699 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002700 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002701 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2702 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002703 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002704 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002705 break;
2706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 }
2708
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002709 std::unique_ptr<CommandEntry> commandEntry =
2710 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002711 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002713 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002714 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715}
2716
2717void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002719 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002720 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002721 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002723 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002724 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002725 ATRACE_NAME(message.c_str());
2726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#if DEBUG_DISPATCH_CYCLE
2728 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002729 "globalScaleFactor=%f, pointerIds=0x%x %s",
2730 connection->getInputChannelName().c_str(), inputTarget.flags,
2731 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2732 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733#endif
2734
2735 // Skip this event if the connection status is not normal.
2736 // We don't want to enqueue additional outbound events if the connection is broken.
2737 if (connection->status != Connection::STATUS_NORMAL) {
2738#if DEBUG_DISPATCH_CYCLE
2739 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741#endif
2742 return;
2743 }
2744
2745 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002746 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2747 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2748 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002749 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002751 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002752 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002753 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002754 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 if (!splitMotionEntry) {
2756 return; // split event was dropped
2757 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002758 if (DEBUG_FOCUS) {
2759 ALOGD("channel '%s' ~ Split motion event.",
2760 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002761 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002762 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002763 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2764 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 return;
2766 }
2767 }
2768
2769 // Not splitting. Enqueue dispatch entries for the event as is.
2770 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2771}
2772
2773void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002774 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002775 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002776 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002777 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002779 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002780 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002781 ATRACE_NAME(message.c_str());
2782 }
2783
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002784 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785
2786 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002787 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002788 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002789 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002791 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002792 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002793 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002795 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002796 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002797 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002798 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799
2800 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002801 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 startDispatchCycleLocked(currentTime, connection);
2803 }
2804}
2805
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002806void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002807 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002808 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002809 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002810 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002811 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2812 connection->getInputChannelName().c_str(),
2813 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002814 ATRACE_NAME(message.c_str());
2815 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002816 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 if (!(inputTargetFlags & dispatchMode)) {
2818 return;
2819 }
2820 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2821
2822 // This is a new event.
2823 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002824 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002825 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002827 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2828 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002829 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002831 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002832 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002833 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002834 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002835 dispatchEntry->resolvedAction = keyEntry.action;
2836 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2839 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2842 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844 return; // skip the inconsistent event
2845 }
2846 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002849 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002850 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002851 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2852 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2853 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2854 static_cast<int32_t>(IdGenerator::Source::OTHER);
2855 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002856 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2857 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2858 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2859 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2860 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2861 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2862 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2863 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2864 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2865 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2866 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002867 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002868 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002869 }
2870 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002871 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2872 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002874 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2875 "event",
2876 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002881 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2883 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2884 }
2885 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2886 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2890 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2893 "event",
2894 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 return; // skip the inconsistent event
2897 }
2898
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002899 dispatchEntry->resolvedEventId =
2900 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2901 ? mIdGenerator.nextId()
2902 : motionEntry.id;
2903 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2904 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2905 ") to MotionEvent(id=0x%" PRIx32 ").",
2906 motionEntry.id, dispatchEntry->resolvedEventId);
2907 ATRACE_NAME(message.c_str());
2908 }
2909
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002910 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002911 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912
2913 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002915 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002916 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2917 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002918 break;
2919 }
Chris Yef59a2f42020-10-16 12:55:26 -07002920 case EventEntry::Type::SENSOR: {
2921 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2922 break;
2923 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002924 case EventEntry::Type::CONFIGURATION_CHANGED:
2925 case EventEntry::Type::DEVICE_RESET: {
2926 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002927 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002928 break;
2929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 }
2931
2932 // Remember that we are waiting for this dispatch to complete.
2933 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002934 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 }
2936
2937 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002938 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002939 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002940}
2941
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002942/**
2943 * This function is purely for debugging. It helps us understand where the user interaction
2944 * was taking place. For example, if user is touching launcher, we will see a log that user
2945 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2946 * We will see both launcher and wallpaper in that list.
2947 * Once the interaction with a particular set of connections starts, no new logs will be printed
2948 * until the set of interacted connections changes.
2949 *
2950 * The following items are skipped, to reduce the logspam:
2951 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2952 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2953 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2954 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2955 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002956 */
2957void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2958 const std::vector<InputTarget>& targets) {
2959 // Skip ACTION_UP events, and all events other than keys and motions
2960 if (entry.type == EventEntry::Type::KEY) {
2961 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2962 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2963 return;
2964 }
2965 } else if (entry.type == EventEntry::Type::MOTION) {
2966 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2967 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2968 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2969 return;
2970 }
2971 } else {
2972 return; // Not a key or a motion
2973 }
2974
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07002975 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002976 std::vector<sp<Connection>> newConnections;
2977 for (const InputTarget& target : targets) {
2978 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2979 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2980 continue; // Skip windows that receive ACTION_OUTSIDE
2981 }
2982
2983 sp<IBinder> token = target.inputChannel->getConnectionToken();
2984 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002985 if (connection == nullptr) {
2986 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002987 }
2988 newConnectionTokens.insert(std::move(token));
2989 newConnections.emplace_back(connection);
2990 }
2991 if (newConnectionTokens == mInteractionConnectionTokens) {
2992 return; // no change
2993 }
2994 mInteractionConnectionTokens = newConnectionTokens;
2995
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002996 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002997 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002998 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002999 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003000 std::string message = "Interaction with: " + targetList;
3001 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003002 message += "<none>";
3003 }
3004 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3005}
3006
chaviwfd6d3512019-03-25 13:23:49 -07003007void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003008 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003009 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003010 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3011 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003012 return;
3013 }
3014
Vishnu Nairc519ff72021-01-21 08:23:08 -08003015 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003016 if (focusedToken == token) {
3017 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003018 return;
3019 }
3020
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003021 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3022 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003023 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003024 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025}
3026
3027void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003029 if (ATRACE_ENABLED()) {
3030 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003031 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003032 ATRACE_NAME(message.c_str());
3033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036#endif
3037
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003038 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3039 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003041 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003042 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003043 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044
3045 // Publish the event.
3046 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003047 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3048 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003049 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3051 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003054 status = connection->inputPublisher
3055 .publishKeyEvent(dispatchEntry->seq,
3056 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3057 keyEntry.source, keyEntry.displayId,
3058 std::move(hmac), dispatchEntry->resolvedAction,
3059 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3060 keyEntry.scanCode, keyEntry.metaState,
3061 keyEntry.repeatCount, keyEntry.downTime,
3062 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003063 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
3065
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003066 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003067 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003070 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003071
chaviw82357092020-01-28 13:13:06 -08003072 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003073 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3075 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003076 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003077 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3078 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003079 // Don't apply window scale here since we don't want scale to affect raw
3080 // coordinates. The scale will be sent back to the client and applied
3081 // later when requesting relative coordinates.
3082 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3083 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 }
3085 usingCoords = scaledCoords;
3086 }
3087 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 // We don't want the dispatch target to know.
3089 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003090 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091 scaledCoords[i].clear();
3092 }
3093 usingCoords = scaledCoords;
3094 }
3095 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003096
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003097 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098
3099 // Publish the motion event.
3100 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003101 .publishMotionEvent(dispatchEntry->seq,
3102 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003103 motionEntry.deviceId, motionEntry.source,
3104 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003105 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003106 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 motionEntry.edgeFlags, motionEntry.metaState,
3109 motionEntry.buttonState,
3110 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003111 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003112 motionEntry.xPrecision, motionEntry.yPrecision,
3113 motionEntry.xCursorPosition,
3114 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003115 dispatchEntry->displaySize.x,
3116 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003117 motionEntry.downTime, motionEntry.eventTime,
3118 motionEntry.pointerCount,
3119 motionEntry.pointerProperties, usingCoords);
3120 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 break;
3122 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003123
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003124 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003126 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003127 focusEntry.id,
3128 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003129 mInTouchMode);
3130 break;
3131 }
3132
Prabir Pradhan99987712020-11-10 18:43:05 -08003133 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3134 const auto& captureEntry =
3135 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3136 status = connection->inputPublisher
3137 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3138 captureEntry.pointerCaptureEnabled);
3139 break;
3140 }
3141
arthurhungb89ccb02020-12-30 16:19:01 +08003142 case EventEntry::Type::DRAG: {
3143 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3144 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3145 dragEntry.id, dragEntry.x,
3146 dragEntry.y,
3147 dragEntry.isExiting);
3148 break;
3149 }
3150
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003151 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003152 case EventEntry::Type::DEVICE_RESET:
3153 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003154 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003155 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
3159
3160 // Check the result.
3161 if (status) {
3162 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003163 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 "This is unexpected because the wait queue is empty, so the pipe "
3166 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003167 "event to it, status=%s(%d)",
3168 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3169 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3171 } else {
3172 // Pipe is full and we are waiting for the app to finish process some events
3173 // before sending more events to it.
3174#if DEBUG_DISPATCH_CYCLE
3175 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003176 "waiting for the application to catch up",
3177 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
3180 } else {
3181 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003182 "status=%s(%d)",
3183 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3184 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3186 }
3187 return;
3188 }
3189
3190 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003191 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3192 connection->outboundQueue.end(),
3193 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003194 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003195 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003196 if (connection->responsive) {
3197 mAnrTracker.insert(dispatchEntry->timeoutTime,
3198 connection->inputChannel->getConnectionToken());
3199 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003200 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
3202}
3203
chaviw09c8d2d2020-08-24 15:48:26 -07003204std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3205 size_t size;
3206 switch (event.type) {
3207 case VerifiedInputEvent::Type::KEY: {
3208 size = sizeof(VerifiedKeyEvent);
3209 break;
3210 }
3211 case VerifiedInputEvent::Type::MOTION: {
3212 size = sizeof(VerifiedMotionEvent);
3213 break;
3214 }
3215 }
3216 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3217 return mHmacKeyManager.sign(start, size);
3218}
3219
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003220const std::array<uint8_t, 32> InputDispatcher::getSignature(
3221 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3222 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3223 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3224 // Only sign events up and down events as the purely move events
3225 // are tied to their up/down counterparts so signing would be redundant.
3226 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3227 verifiedEvent.actionMasked = actionMasked;
3228 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003229 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003230 }
3231 return INVALID_HMAC;
3232}
3233
3234const std::array<uint8_t, 32> InputDispatcher::getSignature(
3235 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3236 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3237 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3238 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003239 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003240}
3241
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003244 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245#if DEBUG_DISPATCH_CYCLE
3246 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248#endif
3249
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 if (connection->status == Connection::STATUS_BROKEN ||
3251 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252 return;
3253 }
3254
3255 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003256 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257}
3258
3259void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003260 const sp<Connection>& connection,
3261 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262#if DEBUG_DISPATCH_CYCLE
3263 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265#endif
3266
3267 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003268 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003269 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003270 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003271 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
3273 // The connection appears to be unrecoverably broken.
3274 // Ignore already broken or zombie connections.
3275 if (connection->status == Connection::STATUS_NORMAL) {
3276 connection->status = Connection::STATUS_BROKEN;
3277
3278 if (notify) {
3279 // Notify other system components.
3280 onDispatchCycleBrokenLocked(currentTime, connection);
3281 }
3282 }
3283}
3284
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003285void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3286 while (!queue.empty()) {
3287 DispatchEntry* dispatchEntry = queue.front();
3288 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003289 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 }
3291}
3292
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003293void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 }
3297 delete dispatchEntry;
3298}
3299
3300int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3301 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3302
3303 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003304 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003306 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 "fd=%d, events=0x%x",
3309 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 return 0; // remove the callback
3311 }
3312
3313 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003314 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3316 if (!(events & ALOOPER_EVENT_INPUT)) {
3317 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 "events=0x%x",
3319 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 return 1;
3321 }
3322
3323 nsecs_t currentTime = now();
3324 bool gotOne = false;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00003325 status_t status = OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 for (;;) {
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003327 Result<InputPublisher::ConsumerResponse> result =
3328 connection->inputPublisher.receiveConsumerResponse();
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00003329 if (!result.ok()) {
3330 status = result.error().code();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 break;
3332 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003333
3334 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3335 const InputPublisher::Finished& finish =
3336 std::get<InputPublisher::Finished>(*result);
3337 d->finishDispatchCycleLocked(currentTime, connection, finish.seq,
3338 finish.handled, finish.consumeTime);
3339 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
3340 // TODO(b/167947340): Report this data to LatencyTracker
3341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 gotOne = true;
3343 }
3344 if (gotOne) {
3345 d->runCommandsLockedInterruptible();
3346 if (status == WOULD_BLOCK) {
3347 return 1;
3348 }
3349 }
3350
3351 notify = status != DEAD_OBJECT || !connection->monitor;
3352 if (notify) {
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003353 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3354 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3355 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 }
3357 } else {
3358 // Monitor channels are never explicitly unregistered.
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003359 // We do it automatically when the remote endpoint is closed so don't warn about them.
arthurhungd352cb32020-04-28 17:09:28 +08003360 const bool stillHaveWindowHandle =
3361 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3362 nullptr;
3363 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 if (notify) {
3365 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 "events=0x%x",
3367 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 }
3369 }
3370
Garfield Tan15601662020-09-22 15:32:38 -07003371 // Remove the channel.
3372 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375}
3376
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003379 for (const auto& [fd, connection] : mConnectionsByFd) {
3380 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 }
3382}
3383
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003385 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003386 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3387 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3388}
3389
3390void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3391 const CancelationOptions& options,
3392 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3393 for (const auto& it : monitorsByDisplay) {
3394 const std::vector<Monitor>& monitors = it.second;
3395 for (const Monitor& monitor : monitors) {
3396 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003397 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003398 }
3399}
3400
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003402 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003403 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003404 if (connection == nullptr) {
3405 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003407
3408 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409}
3410
3411void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3412 const sp<Connection>& connection, const CancelationOptions& options) {
3413 if (connection->status == Connection::STATUS_BROKEN) {
3414 return;
3415 }
3416
3417 nsecs_t currentTime = now();
3418
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003419 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003420 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003422 if (cancelationEvents.empty()) {
3423 return;
3424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003426 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3427 "with reality: %s, mode=%d.",
3428 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3429 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003431
3432 InputTarget target;
3433 sp<InputWindowHandle> windowHandle =
3434 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3435 if (windowHandle != nullptr) {
3436 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003437 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003438 target.globalScaleFactor = windowInfo->globalScaleFactor;
3439 }
3440 target.inputChannel = connection->inputChannel;
3441 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3442
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003443 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003444 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003445 switch (cancelationEventEntry->type) {
3446 case EventEntry::Type::KEY: {
3447 logOutboundKeyDetails("cancel - ",
3448 static_cast<const KeyEntry&>(*cancelationEventEntry));
3449 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003451 case EventEntry::Type::MOTION: {
3452 logOutboundMotionDetails("cancel - ",
3453 static_cast<const MotionEntry&>(*cancelationEventEntry));
3454 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003456 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003457 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3458 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003459 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003460 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003461 break;
3462 }
3463 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003464 case EventEntry::Type::DEVICE_RESET:
3465 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003466 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003467 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003468 break;
3469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470 }
3471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003472 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3473 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003475
3476 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477}
3478
Svet Ganov5d3bc372020-01-26 23:11:07 -08003479void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3480 const sp<Connection>& connection) {
3481 if (connection->status == Connection::STATUS_BROKEN) {
3482 return;
3483 }
3484
3485 nsecs_t currentTime = now();
3486
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003487 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003488 connection->inputState.synthesizePointerDownEvents(currentTime);
3489
3490 if (downEvents.empty()) {
3491 return;
3492 }
3493
3494#if DEBUG_OUTBOUND_EVENT_DETAILS
3495 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3496 connection->getInputChannelName().c_str(), downEvents.size());
3497#endif
3498
3499 InputTarget target;
3500 sp<InputWindowHandle> windowHandle =
3501 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3502 if (windowHandle != nullptr) {
3503 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003504 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003505 target.globalScaleFactor = windowInfo->globalScaleFactor;
3506 }
3507 target.inputChannel = connection->inputChannel;
3508 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3509
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003510 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003511 switch (downEventEntry->type) {
3512 case EventEntry::Type::MOTION: {
3513 logOutboundMotionDetails("down - ",
3514 static_cast<const MotionEntry&>(*downEventEntry));
3515 break;
3516 }
3517
3518 case EventEntry::Type::KEY:
3519 case EventEntry::Type::FOCUS:
3520 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003521 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003522 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003523 case EventEntry::Type::SENSOR:
3524 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003525 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003526 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003527 break;
3528 }
3529 }
3530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003531 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3532 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003533 }
3534
3535 startDispatchCycleLocked(currentTime, connection);
3536}
3537
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003538std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3539 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 ALOG_ASSERT(pointerIds.value != 0);
3541
3542 uint32_t splitPointerIndexMap[MAX_POINTERS];
3543 PointerProperties splitPointerProperties[MAX_POINTERS];
3544 PointerCoords splitPointerCoords[MAX_POINTERS];
3545
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003546 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 uint32_t splitPointerCount = 0;
3548
3549 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003550 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003552 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 uint32_t pointerId = uint32_t(pointerProperties.id);
3554 if (pointerIds.hasBit(pointerId)) {
3555 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3556 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3557 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003558 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 splitPointerCount += 1;
3560 }
3561 }
3562
3563 if (splitPointerCount != pointerIds.count()) {
3564 // This is bad. We are missing some of the pointers that we expected to deliver.
3565 // Most likely this indicates that we received an ACTION_MOVE events that has
3566 // different pointer ids than we expected based on the previous ACTION_DOWN
3567 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3568 // in this way.
3569 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003570 "we expected there to be %d pointers. This probably means we received "
3571 "a broken sequence of pointer ids from the input device.",
3572 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003573 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
3575
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003576 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003578 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3579 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3581 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003582 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 uint32_t pointerId = uint32_t(pointerProperties.id);
3584 if (pointerIds.hasBit(pointerId)) {
3585 if (pointerIds.count() == 1) {
3586 // The first/last pointer went down/up.
3587 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003589 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3590 ? AMOTION_EVENT_ACTION_CANCEL
3591 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 } else {
3593 // A secondary pointer went down/up.
3594 uint32_t splitPointerIndex = 0;
3595 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3596 splitPointerIndex += 1;
3597 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003598 action = maskedAction |
3599 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 }
3601 } else {
3602 // An unrelated pointer changed.
3603 action = AMOTION_EVENT_ACTION_MOVE;
3604 }
3605 }
3606
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003607 int32_t newId = mIdGenerator.nextId();
3608 if (ATRACE_ENABLED()) {
3609 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3610 ") to MotionEvent(id=0x%" PRIx32 ").",
3611 originalMotionEntry.id, newId);
3612 ATRACE_NAME(message.c_str());
3613 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003614 std::unique_ptr<MotionEntry> splitMotionEntry =
3615 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3616 originalMotionEntry.deviceId, originalMotionEntry.source,
3617 originalMotionEntry.displayId,
3618 originalMotionEntry.policyFlags, action,
3619 originalMotionEntry.actionButton,
3620 originalMotionEntry.flags, originalMotionEntry.metaState,
3621 originalMotionEntry.buttonState,
3622 originalMotionEntry.classification,
3623 originalMotionEntry.edgeFlags,
3624 originalMotionEntry.xPrecision,
3625 originalMotionEntry.yPrecision,
3626 originalMotionEntry.xCursorPosition,
3627 originalMotionEntry.yCursorPosition,
3628 originalMotionEntry.downTime, splitPointerCount,
3629 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003631 if (originalMotionEntry.injectionState) {
3632 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 splitMotionEntry->injectionState->refCount += 1;
3634 }
3635
3636 return splitMotionEntry;
3637}
3638
3639void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3640#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003641 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642#endif
3643
3644 bool needWake;
3645 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003646 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003648 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3649 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3650 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 } // release lock
3652
3653 if (needWake) {
3654 mLooper->wake();
3655 }
3656}
3657
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003658/**
3659 * If one of the meta shortcuts is detected, process them here:
3660 * Meta + Backspace -> generate BACK
3661 * Meta + Enter -> generate HOME
3662 * This will potentially overwrite keyCode and metaState.
3663 */
3664void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003665 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003666 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3667 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3668 if (keyCode == AKEYCODE_DEL) {
3669 newKeyCode = AKEYCODE_BACK;
3670 } else if (keyCode == AKEYCODE_ENTER) {
3671 newKeyCode = AKEYCODE_HOME;
3672 }
3673 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003674 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003675 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003676 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003677 keyCode = newKeyCode;
3678 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3679 }
3680 } else if (action == AKEY_EVENT_ACTION_UP) {
3681 // In order to maintain a consistent stream of up and down events, check to see if the key
3682 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3683 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003684 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003685 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003686 auto replacementIt = mReplacedKeys.find(replacement);
3687 if (replacementIt != mReplacedKeys.end()) {
3688 keyCode = replacementIt->second;
3689 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003690 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3691 }
3692 }
3693}
3694
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3696#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003697 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3698 "policyFlags=0x%x, action=0x%x, "
3699 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3700 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3701 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3702 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703#endif
3704 if (!validateKeyEvent(args->action)) {
3705 return;
3706 }
3707
3708 uint32_t policyFlags = args->policyFlags;
3709 int32_t flags = args->flags;
3710 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003711 // InputDispatcher tracks and generates key repeats on behalf of
3712 // whatever notifies it, so repeatCount should always be set to 0
3713 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3715 policyFlags |= POLICY_FLAG_VIRTUAL;
3716 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 if (policyFlags & POLICY_FLAG_FUNCTION) {
3719 metaState |= AMETA_FUNCTION_ON;
3720 }
3721
3722 policyFlags |= POLICY_FLAG_TRUSTED;
3723
Michael Wright78f24442014-08-06 15:55:28 -07003724 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003725 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003726
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003728 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003729 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3730 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731
Michael Wright2b3c3302018-03-02 17:19:13 +00003732 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003734 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3735 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003736 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 bool needWake;
3740 { // acquire lock
3741 mLock.lock();
3742
3743 if (shouldSendKeyToInputFilterLocked(args)) {
3744 mLock.unlock();
3745
3746 policyFlags |= POLICY_FLAG_FILTERED;
3747 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3748 return; // event was consumed by the filter
3749 }
3750
3751 mLock.lock();
3752 }
3753
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003754 std::unique_ptr<KeyEntry> newEntry =
3755 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3756 args->displayId, policyFlags, args->action, flags,
3757 keyCode, args->scanCode, metaState, repeatCount,
3758 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003760 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 mLock.unlock();
3762 } // release lock
3763
3764 if (needWake) {
3765 mLooper->wake();
3766 }
3767}
3768
3769bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3770 return mInputFilterEnabled;
3771}
3772
3773void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3774#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003775 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3776 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003777 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3778 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003779 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003780 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3781 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3782 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3783 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 for (uint32_t i = 0; i < args->pointerCount; i++) {
3785 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 "x=%f, y=%f, pressure=%f, size=%f, "
3787 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3788 "orientation=%f",
3789 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3790 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3791 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3792 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3793 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3794 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3795 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3796 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3797 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3798 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 }
3800#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003801 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3802 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 return;
3804 }
3805
3806 uint32_t policyFlags = args->policyFlags;
3807 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003808
3809 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003810 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003811 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3812 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815
3816 bool needWake;
3817 { // acquire lock
3818 mLock.lock();
3819
3820 if (shouldSendMotionToInputFilterLocked(args)) {
3821 mLock.unlock();
3822
3823 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003824 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003825 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3826 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003827 args->metaState, args->buttonState, args->classification, transform,
3828 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003829 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3830 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003831 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
3833 policyFlags |= POLICY_FLAG_FILTERED;
3834 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3835 return; // event was consumed by the filter
3836 }
3837
3838 mLock.lock();
3839 }
3840
3841 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003842 std::unique_ptr<MotionEntry> newEntry =
3843 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3844 args->source, args->displayId, policyFlags,
3845 args->action, args->actionButton, args->flags,
3846 args->metaState, args->buttonState,
3847 args->classification, args->edgeFlags,
3848 args->xPrecision, args->yPrecision,
3849 args->xCursorPosition, args->yCursorPosition,
3850 args->downTime, args->pointerCount,
3851 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003853 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 mLock.unlock();
3855 } // release lock
3856
3857 if (needWake) {
3858 mLooper->wake();
3859 }
3860}
3861
Chris Yef59a2f42020-10-16 12:55:26 -07003862void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3863#if DEBUG_INBOUND_EVENT_DETAILS
3864 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3865 " sensorType=%s",
3866 args->id, args->eventTime, args->deviceId, args->source,
3867 NamedEnum::string(args->sensorType).c_str());
3868#endif
3869
3870 bool needWake;
3871 { // acquire lock
3872 mLock.lock();
3873
3874 // Just enqueue a new sensor event.
3875 std::unique_ptr<SensorEntry> newEntry =
3876 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3877 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3878 args->sensorType, args->accuracy,
3879 args->accuracyChanged, args->values);
3880
3881 needWake = enqueueInboundEventLocked(std::move(newEntry));
3882 mLock.unlock();
3883 } // release lock
3884
3885 if (needWake) {
3886 mLooper->wake();
3887 }
3888}
3889
Chris Yefb552902021-02-03 17:18:37 -08003890void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3891#if DEBUG_INBOUND_EVENT_DETAILS
3892 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3893 args->deviceId, args->isOn);
3894#endif
3895 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3896}
3897
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003899 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900}
3901
3902void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3903#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003904 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003905 "switchMask=0x%08x",
3906 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907#endif
3908
3909 uint32_t policyFlags = args->policyFlags;
3910 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003911 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912}
3913
3914void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3915#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003916 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3917 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918#endif
3919
3920 bool needWake;
3921 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003922 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003924 std::unique_ptr<DeviceResetEntry> newEntry =
3925 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3926 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 } // release lock
3928
3929 if (needWake) {
3930 mLooper->wake();
3931 }
3932}
3933
Prabir Pradhan7e186182020-11-10 13:56:45 -08003934void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3935#if DEBUG_INBOUND_EVENT_DETAILS
3936 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3937 args->enabled ? "true" : "false");
3938#endif
3939
Prabir Pradhan99987712020-11-10 18:43:05 -08003940 bool needWake;
3941 { // acquire lock
3942 std::scoped_lock _l(mLock);
3943 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3944 args->enabled);
3945 needWake = enqueueInboundEventLocked(std::move(entry));
3946 } // release lock
3947
3948 if (needWake) {
3949 mLooper->wake();
3950 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003951}
3952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953InputEventInjectionResult InputDispatcher::injectInputEvent(
3954 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3955 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956#if DEBUG_INBOUND_EVENT_DETAILS
3957 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003958 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3959 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003961 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
3963 policyFlags |= POLICY_FLAG_INJECTED;
3964 if (hasInjectionPermission(injectorPid, injectorUid)) {
3965 policyFlags |= POLICY_FLAG_TRUSTED;
3966 }
3967
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003968 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003971 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3972 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003974 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003977 int32_t flags = incomingKey.getFlags();
3978 int32_t keyCode = incomingKey.getKeyCode();
3979 int32_t metaState = incomingKey.getMetaState();
3980 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003982 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003983 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003984 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3985 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3986 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003988 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3989 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003990 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003991
3992 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3993 android::base::Timer t;
3994 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3995 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3996 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3997 std::to_string(t.duration().count()).c_str());
3998 }
3999 }
4000
4001 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::unique_ptr<KeyEntry> injectedEntry =
4003 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
4004 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
4005 incomingKey.getDisplayId(), policyFlags, action,
4006 flags, keyCode, incomingKey.getScanCode(), metaState,
4007 incomingKey.getRepeatCount(),
4008 incomingKey.getDownTime());
4009 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 }
4012
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004013 case AINPUT_EVENT_TYPE_MOTION: {
4014 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
4015 int32_t action = motionEvent->getAction();
4016 size_t pointerCount = motionEvent->getPointerCount();
4017 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
4018 int32_t actionButton = motionEvent->getActionButton();
4019 int32_t displayId = motionEvent->getDisplayId();
4020 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004021 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 }
4023
4024 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4025 nsecs_t eventTime = motionEvent->getEventTime();
4026 android::base::Timer t;
4027 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4028 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4029 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4030 std::to_string(t.duration().count()).c_str());
4031 }
4032 }
4033
4034 mLock.lock();
4035 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
4036 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004037 std::unique_ptr<MotionEntry> injectedEntry =
4038 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4039 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4040 motionEvent->getDisplayId(), policyFlags, action,
4041 actionButton, motionEvent->getFlags(),
4042 motionEvent->getMetaState(),
4043 motionEvent->getButtonState(),
4044 motionEvent->getClassification(),
4045 motionEvent->getEdgeFlags(),
4046 motionEvent->getXPrecision(),
4047 motionEvent->getYPrecision(),
4048 motionEvent->getRawXCursorPosition(),
4049 motionEvent->getRawYCursorPosition(),
4050 motionEvent->getDownTime(),
4051 uint32_t(pointerCount), pointerProperties,
4052 samplePointerCoords, motionEvent->getXOffset(),
4053 motionEvent->getYOffset());
4054 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
4056 sampleEventTimes += 1;
4057 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004058 std::unique_ptr<MotionEntry> nextInjectedEntry =
4059 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4060 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4061 motionEvent->getDisplayId(), policyFlags,
4062 action, actionButton, motionEvent->getFlags(),
4063 motionEvent->getMetaState(),
4064 motionEvent->getButtonState(),
4065 motionEvent->getClassification(),
4066 motionEvent->getEdgeFlags(),
4067 motionEvent->getXPrecision(),
4068 motionEvent->getYPrecision(),
4069 motionEvent->getRawXCursorPosition(),
4070 motionEvent->getRawYCursorPosition(),
4071 motionEvent->getDownTime(),
4072 uint32_t(pointerCount), pointerProperties,
4073 samplePointerCoords,
4074 motionEvent->getXOffset(),
4075 motionEvent->getYOffset());
4076 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 }
4078 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004082 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004083 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 }
4085
4086 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004087 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 injectionState->injectionIsAsync = true;
4089 }
4090
4091 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004092 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093
4094 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004095 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004096 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004097 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
4099
4100 mLock.unlock();
4101
4102 if (needWake) {
4103 mLooper->wake();
4104 }
4105
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004106 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004108 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004110 if (syncMode == InputEventInjectionSync::NONE) {
4111 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 } else {
4113 for (;;) {
4114 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004115 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 break;
4117 }
4118
4119 nsecs_t remainingTimeout = endTime - now();
4120 if (remainingTimeout <= 0) {
4121#if DEBUG_INJECTION
4122 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004125 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 break;
4127 }
4128
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004129 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 }
4131
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004132 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4133 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 while (injectionState->pendingForegroundDispatches != 0) {
4135#if DEBUG_INJECTION
4136 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138#endif
4139 nsecs_t remainingTimeout = endTime - now();
4140 if (remainingTimeout <= 0) {
4141#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4143 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004145 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 break;
4147 }
4148
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004149 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 }
4151 }
4152 }
4153
4154 injectionState->release();
4155 } // release lock
4156
4157#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004158 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004159 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160#endif
4161
4162 return injectionResult;
4163}
4164
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004165std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004166 std::array<uint8_t, 32> calculatedHmac;
4167 std::unique_ptr<VerifiedInputEvent> result;
4168 switch (event.getType()) {
4169 case AINPUT_EVENT_TYPE_KEY: {
4170 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4171 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4172 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004173 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004174 break;
4175 }
4176 case AINPUT_EVENT_TYPE_MOTION: {
4177 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4178 VerifiedMotionEvent verifiedMotionEvent =
4179 verifiedMotionEventFromMotionEvent(motionEvent);
4180 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004181 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004182 break;
4183 }
4184 default: {
4185 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4186 return nullptr;
4187 }
4188 }
4189 if (calculatedHmac == INVALID_HMAC) {
4190 return nullptr;
4191 }
4192 if (calculatedHmac != event.getHmac()) {
4193 return nullptr;
4194 }
4195 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004196}
4197
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004199 return injectorUid == 0 ||
4200 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201}
4202
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004203void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004204 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004205 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 if (injectionState) {
4207#if DEBUG_INJECTION
4208 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 "injectorPid=%d, injectorUid=%d",
4210 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211#endif
4212
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004213 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 // Log the outcome since the injector did not wait for the injection result.
4215 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004216 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 ALOGV("Asynchronous input event injection succeeded.");
4218 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 ALOGW("Asynchronous input event injection failed.");
4221 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004222 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 ALOGW("Asynchronous input event injection permission denied.");
4224 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004225 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 ALOGW("Asynchronous input event injection timed out.");
4227 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004228 case InputEventInjectionResult::PENDING:
4229 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4230 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232 }
4233
4234 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004235 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237}
4238
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004239void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4240 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 if (injectionState) {
4242 injectionState->pendingForegroundDispatches += 1;
4243 }
4244}
4245
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004246void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4247 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 if (injectionState) {
4249 injectionState->pendingForegroundDispatches -= 1;
4250
4251 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004252 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 }
4254 }
4255}
4256
Vishnu Nairad321cd2020-08-20 16:40:21 -07004257const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004258 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004259 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4260 auto it = mWindowHandlesByDisplay.find(displayId);
4261 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004262}
4263
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004265 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004266 if (windowHandleToken == nullptr) {
4267 return nullptr;
4268 }
4269
Arthur Hungb92218b2018-08-14 12:00:21 +08004270 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004271 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004272 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004273 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004274 return windowHandle;
4275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 }
4277 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004278 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279}
4280
Vishnu Nairad321cd2020-08-20 16:40:21 -07004281sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4282 int displayId) const {
4283 if (windowHandleToken == nullptr) {
4284 return nullptr;
4285 }
4286
4287 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4288 if (windowHandle->getToken() == windowHandleToken) {
4289 return windowHandle;
4290 }
4291 }
4292 return nullptr;
4293}
4294
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004295sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4296 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004297 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004298 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004299 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004300 if (handle->getId() == windowHandle->getId() &&
4301 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004302 if (windowHandle->getInfo()->displayId != it.first) {
4303 ALOGE("Found window %s in display %" PRId32
4304 ", but it should belong to display %" PRId32,
4305 windowHandle->getName().c_str(), it.first,
4306 windowHandle->getInfo()->displayId);
4307 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004308 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004312 return nullptr;
4313}
4314
4315sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4316 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4317 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318}
4319
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004320bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4321 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4322 const bool noInputChannel =
4323 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4324 if (connection != nullptr && noInputChannel) {
4325 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4326 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4327 return false;
4328 }
4329
4330 if (connection == nullptr) {
4331 if (!noInputChannel) {
4332 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4333 }
4334 return false;
4335 }
4336 if (!connection->responsive) {
4337 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4338 return false;
4339 }
4340 return true;
4341}
4342
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004343std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4344 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004345 size_t count = mInputChannelsByToken.count(token);
4346 if (count == 0) {
4347 return nullptr;
4348 }
4349 return mInputChannelsByToken.at(token);
4350}
4351
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004352void InputDispatcher::updateWindowHandlesForDisplayLocked(
4353 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4354 if (inputWindowHandles.empty()) {
4355 // Remove all handles on a display if there are no windows left.
4356 mWindowHandlesByDisplay.erase(displayId);
4357 return;
4358 }
4359
4360 // Since we compare the pointer of input window handles across window updates, we need
4361 // to make sure the handle object for the same window stays unchanged across updates.
4362 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004363 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004364 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004365 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004366 }
4367
4368 std::vector<sp<InputWindowHandle>> newHandles;
4369 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4370 if (!handle->updateInfo()) {
4371 // handle no longer valid
4372 continue;
4373 }
4374
4375 const InputWindowInfo* info = handle->getInfo();
4376 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4377 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4378 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004379 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4380 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4381 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004382 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004383 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004384 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004385 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004386 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004387 }
4388
4389 if (info->displayId != displayId) {
4390 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4391 handle->getName().c_str(), displayId, info->displayId);
4392 continue;
4393 }
4394
Robert Carredd13602020-04-13 17:24:34 -07004395 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4396 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004397 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004398 oldHandle->updateFrom(handle);
4399 newHandles.push_back(oldHandle);
4400 } else {
4401 newHandles.push_back(handle);
4402 }
4403 }
4404
4405 // Insert or replace
4406 mWindowHandlesByDisplay[displayId] = newHandles;
4407}
4408
Arthur Hung72d8dc32020-03-28 00:48:39 +00004409void InputDispatcher::setInputWindows(
4410 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4411 { // acquire lock
4412 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004413 for (const auto& [displayId, handles] : handlesPerDisplay) {
4414 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004415 }
4416 }
4417 // Wake up poll loop since it may need to make new input dispatching choices.
4418 mLooper->wake();
4419}
4420
Arthur Hungb92218b2018-08-14 12:00:21 +08004421/**
4422 * Called from InputManagerService, update window handle list by displayId that can receive input.
4423 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4424 * If set an empty list, remove all handles from the specific display.
4425 * For focused handle, check if need to change and send a cancel event to previous one.
4426 * For removed handle, check if need to send a cancel event if already in touch.
4427 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004428void InputDispatcher::setInputWindowsLocked(
4429 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004430 if (DEBUG_FOCUS) {
4431 std::string windowList;
4432 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4433 windowList += iwh->getName() + " ";
4434 }
4435 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004438 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4439 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4440 const bool noInputWindow =
4441 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4442 if (noInputWindow && window->getToken() != nullptr) {
4443 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4444 window->getName().c_str());
4445 window->releaseChannel();
4446 }
4447 }
4448
Arthur Hung72d8dc32020-03-28 00:48:39 +00004449 // Copy old handles for release if they are no longer present.
4450 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451
Arthur Hung72d8dc32020-03-28 00:48:39 +00004452 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004453
Vishnu Nair958da932020-08-21 17:12:37 -07004454 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4455 if (mLastHoverWindowHandle &&
4456 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4457 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004458 mLastHoverWindowHandle = nullptr;
4459 }
4460
Vishnu Nairc519ff72021-01-21 08:23:08 -08004461 std::optional<FocusResolver::FocusChanges> changes =
4462 mFocusResolver.setInputWindows(displayId, windowHandles);
4463 if (changes) {
4464 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004467 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4468 mTouchStatesByDisplay.find(displayId);
4469 if (stateIt != mTouchStatesByDisplay.end()) {
4470 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004471 for (size_t i = 0; i < state.windows.size();) {
4472 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004473 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004474 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004475 ALOGD("Touched window was removed: %s in display %" PRId32,
4476 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004477 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004478 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004479 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4480 if (touchedInputChannel != nullptr) {
4481 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4482 "touched window was removed");
4483 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004485 state.windows.erase(state.windows.begin() + i);
4486 } else {
4487 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 }
4489 }
arthurhungb89ccb02020-12-30 16:19:01 +08004490
arthurhung6d4bed92021-03-17 11:59:33 +08004491 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004492 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004493 if (mDragState &&
4494 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004495 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004496 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004497 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004498 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004499
Arthur Hung72d8dc32020-03-28 00:48:39 +00004500 // Release information for windows that are no longer present.
4501 // This ensures that unused input channels are released promptly.
4502 // Otherwise, they might stick around until the window handle is destroyed
4503 // which might not happen until the next GC.
4504 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004505 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004506 if (DEBUG_FOCUS) {
4507 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004508 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004509 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004510 // To avoid making too many calls into the compat framework, only
4511 // check for window flags when windows are going away.
4512 // TODO(b/157929241) : delete this. This is only needed temporarily
4513 // in order to gather some data about the flag usage
4514 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4515 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4516 oldWindowHandle->getName().c_str());
4517 if (mCompatService != nullptr) {
4518 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4519 oldWindowHandle->getInfo()->ownerUid);
4520 }
4521 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004522 }
chaviw291d88a2019-02-14 10:33:58 -08004523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524}
4525
4526void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004527 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004528 if (DEBUG_FOCUS) {
4529 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4530 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4531 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004532 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004533 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534
Chris Yea209fde2020-07-22 13:54:51 -07004535 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004536 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004538 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4539 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540 }
4541
Chris Yea209fde2020-07-22 13:54:51 -07004542 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004543 if (inputApplicationHandle != nullptr) {
4544 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4545 } else {
4546 mFocusedApplicationHandlesByDisplay.erase(displayId);
4547 }
4548
4549 // No matter what the old focused application was, stop waiting on it because it is
4550 // no longer focused.
4551 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 } // release lock
4553
4554 // Wake up poll loop since it may need to make new input dispatching choices.
4555 mLooper->wake();
4556}
4557
Tiger Huang721e26f2018-07-24 22:26:19 +08004558/**
4559 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4560 * the display not specified.
4561 *
4562 * We track any unreleased events for each window. If a window loses the ability to receive the
4563 * released event, we will send a cancel event to it. So when the focused display is changed, we
4564 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4565 * display. The display-specified events won't be affected.
4566 */
4567void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004568 if (DEBUG_FOCUS) {
4569 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4570 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004571 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004572 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004573
4574 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004575 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004576 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004577 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004578 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004579 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004580 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581 CancelationOptions
4582 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4583 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004584 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004585 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4586 }
4587 }
4588 mFocusedDisplayId = displayId;
4589
Chris Ye3c2d6f52020-08-09 10:39:48 -07004590 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004591 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004592 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004593
Vishnu Nairad321cd2020-08-20 16:40:21 -07004594 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004595 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004596 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004597 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004598 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004599 }
4600 }
4601 }
4602
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004603 if (DEBUG_FOCUS) {
4604 logDispatchStateLocked();
4605 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004606 } // release lock
4607
4608 // Wake up poll loop since it may need to make new input dispatching choices.
4609 mLooper->wake();
4610}
4611
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004613 if (DEBUG_FOCUS) {
4614 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616
4617 bool changed;
4618 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004619 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620
4621 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4622 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004623 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 }
4625
4626 if (mDispatchEnabled && !enabled) {
4627 resetAndDropEverythingLocked("dispatcher is being disabled");
4628 }
4629
4630 mDispatchEnabled = enabled;
4631 mDispatchFrozen = frozen;
4632 changed = true;
4633 } else {
4634 changed = false;
4635 }
4636
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004637 if (DEBUG_FOCUS) {
4638 logDispatchStateLocked();
4639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 } // release lock
4641
4642 if (changed) {
4643 // Wake up poll loop since it may need to make new input dispatching choices.
4644 mLooper->wake();
4645 }
4646}
4647
4648void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004649 if (DEBUG_FOCUS) {
4650 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652
4653 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004654 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655
4656 if (mInputFilterEnabled == enabled) {
4657 return;
4658 }
4659
4660 mInputFilterEnabled = enabled;
4661 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4662 } // release lock
4663
4664 // Wake up poll loop since there might be work to do to drop everything.
4665 mLooper->wake();
4666}
4667
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004668void InputDispatcher::setInTouchMode(bool inTouchMode) {
4669 std::scoped_lock lock(mLock);
4670 mInTouchMode = inTouchMode;
4671}
4672
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004673void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4674 if (opacity < 0 || opacity > 1) {
4675 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4676 return;
4677 }
4678
4679 std::scoped_lock lock(mLock);
4680 mMaximumObscuringOpacityForTouch = opacity;
4681}
4682
4683void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4684 std::scoped_lock lock(mLock);
4685 mBlockUntrustedTouchesMode = mode;
4686}
4687
arthurhungb89ccb02020-12-30 16:19:01 +08004688bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4689 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004690 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004691 if (DEBUG_FOCUS) {
4692 ALOGD("Trivial transfer to same window.");
4693 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004694 return true;
4695 }
4696
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004698 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699
chaviwfbe5d9c2018-12-26 12:23:37 -08004700 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4701 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004702 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004703 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 return false;
4705 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004706 if (DEBUG_FOCUS) {
4707 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4708 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004711 if (DEBUG_FOCUS) {
4712 ALOGD("Cannot transfer focus because windows are on different displays.");
4713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 return false;
4715 }
4716
4717 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004718 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4719 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004720 for (size_t i = 0; i < state.windows.size(); i++) {
4721 const TouchedWindow& touchedWindow = state.windows[i];
4722 if (touchedWindow.windowHandle == fromWindowHandle) {
4723 int32_t oldTargetFlags = touchedWindow.targetFlags;
4724 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004726 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004728 int32_t newTargetFlags = oldTargetFlags &
4729 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4730 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004731 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732
arthurhungb89ccb02020-12-30 16:19:01 +08004733 // Store the dragging window.
4734 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004735 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004736 }
4737
Jeff Brownf086ddb2014-02-11 14:28:48 -08004738 found = true;
4739 goto Found;
4740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 }
4742 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004745 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004746 if (DEBUG_FOCUS) {
4747 ALOGD("Focus transfer failed because from window did not have focus.");
4748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 return false;
4750 }
4751
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004752 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4753 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004754 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004755 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004756 CancelationOptions
4757 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4758 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004760 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 }
4762
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004763 if (DEBUG_FOCUS) {
4764 logDispatchStateLocked();
4765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 } // release lock
4767
4768 // Wake up poll loop since it may need to make new input dispatching choices.
4769 mLooper->wake();
4770 return true;
4771}
4772
4773void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004774 if (DEBUG_FOCUS) {
4775 ALOGD("Resetting and dropping all events (%s).", reason);
4776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777
4778 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4779 synthesizeCancelationEventsForAllConnectionsLocked(options);
4780
4781 resetKeyRepeatLocked();
4782 releasePendingEventLocked();
4783 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004784 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004786 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004787 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004789 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790}
4791
4792void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004793 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 dumpDispatchStateLocked(dump);
4795
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004796 std::istringstream stream(dump);
4797 std::string line;
4798
4799 while (std::getline(stream, line, '\n')) {
4800 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802}
4803
Prabir Pradhan99987712020-11-10 18:43:05 -08004804std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4805 std::string dump;
4806
4807 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4808 toString(mFocusedWindowRequestedPointerCapture));
4809
4810 std::string windowName = "None";
4811 if (mWindowTokenWithPointerCapture) {
4812 const sp<InputWindowHandle> captureWindowHandle =
4813 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4814 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4815 : "token has capture without window";
4816 }
4817 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4818
4819 return dump;
4820}
4821
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004822void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004823 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4824 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4825 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004826 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827
Tiger Huang721e26f2018-07-24 22:26:19 +08004828 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4829 dump += StringPrintf(INDENT "FocusedApplications:\n");
4830 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4831 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004832 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004833 const std::chrono::duration timeout =
4834 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004835 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004836 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004837 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004840 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004842
Vishnu Nairc519ff72021-01-21 08:23:08 -08004843 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004844 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004846 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004847 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004848 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4849 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004850 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004851 state.displayId, toString(state.down), toString(state.split),
4852 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004853 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004854 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004855 for (size_t i = 0; i < state.windows.size(); i++) {
4856 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004857 dump += StringPrintf(INDENT4
4858 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4859 i, touchedWindow.windowHandle->getName().c_str(),
4860 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004861 }
4862 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004863 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004864 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004865 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004866 dump += INDENT3 "Portal windows:\n";
4867 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004868 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004869 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4870 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004871 }
4872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004875 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
4877
arthurhung6d4bed92021-03-17 11:59:33 +08004878 if (mDragState) {
4879 dump += StringPrintf(INDENT "DragState:\n");
4880 mDragState->dump(dump, INDENT2);
4881 }
4882
Arthur Hungb92218b2018-08-14 12:00:21 +08004883 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004884 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004885 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004886 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004887 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004888 dump += INDENT2 "Windows:\n";
4889 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004890 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004891 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004893 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004894 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004895 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004896 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004897 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004898 "applicationInfo.name=%s, "
4899 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004900 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004901 i, windowInfo->name.c_str(), windowInfo->id,
4902 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004903 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004904 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004905 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004906 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004907 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004908 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004909 windowInfo->frameLeft, windowInfo->frameTop,
4910 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004911 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004912 windowInfo->applicationInfo.name.c_str(),
4913 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004914 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004915 dump += StringPrintf(", inputFeatures=%s",
4916 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004917 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004918 "ms, trustedOverlay=%s, hasToken=%s, "
4919 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004920 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004921 millis(windowInfo->dispatchingTimeout),
4922 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004923 toString(windowInfo->token != nullptr),
4924 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004925 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004926 }
4927 } else {
4928 dump += INDENT2 "Windows: <none>\n";
4929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 }
4931 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004932 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 }
4934
Michael Wright3dd60e22019-03-27 22:06:44 +00004935 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004936 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004937 const std::vector<Monitor>& monitors = it.second;
4938 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4939 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004940 }
4941 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004942 const std::vector<Monitor>& monitors = it.second;
4943 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4944 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004947 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 }
4949
4950 nsecs_t currentTime = now();
4951
4952 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004953 if (!mRecentQueue.empty()) {
4954 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004955 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004956 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004957 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004958 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
4960 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004961 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962 }
4963
4964 // Dump event currently being dispatched.
4965 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004966 dump += INDENT "PendingEvent:\n";
4967 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004968 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004969 dump += StringPrintf(", age=%" PRId64 "ms\n",
4970 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004972 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 }
4974
4975 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004976 if (!mInboundQueue.empty()) {
4977 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004978 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004979 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004980 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004981 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 }
4983 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004984 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985 }
4986
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004987 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004988 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004989 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4990 const KeyReplacement& replacement = pair.first;
4991 int32_t newKeyCode = pair.second;
4992 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004993 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004994 }
4995 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004996 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004997 }
4998
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004999 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005000 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005001 for (const auto& pair : mConnectionsByFd) {
5002 const sp<Connection>& connection = pair.second;
5003 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005004 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005005 pair.first, connection->getInputChannelName().c_str(),
5006 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005007 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005009 if (!connection->outboundQueue.empty()) {
5010 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5011 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005012 dump += dumpQueue(connection->outboundQueue, currentTime);
5013
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005015 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016 }
5017
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005018 if (!connection->waitQueue.empty()) {
5019 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5020 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005021 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005023 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 }
5025 }
5026 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005027 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028 }
5029
5030 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005031 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5032 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005034 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 }
5036
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005037 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005038 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5039 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5040 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041}
5042
Michael Wright3dd60e22019-03-27 22:06:44 +00005043void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5044 const size_t numMonitors = monitors.size();
5045 for (size_t i = 0; i < numMonitors; i++) {
5046 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005047 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005048 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5049 dump += "\n";
5050 }
5051}
5052
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005053Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005054#if DEBUG_CHANNEL_CREATION
5055 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056#endif
5057
Garfield Tan15601662020-09-22 15:32:38 -07005058 std::shared_ptr<InputChannel> serverChannel;
5059 std::unique_ptr<InputChannel> clientChannel;
5060 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5061
5062 if (result) {
5063 return base::Error(result) << "Failed to open input channel pair with name " << name;
5064 }
5065
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005067 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07005068 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069
Garfield Tan15601662020-09-22 15:32:38 -07005070 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005071 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005072 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
5075 } // release lock
5076
5077 // Wake the looper because some connections have changed.
5078 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005079 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080}
5081
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005082Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5083 bool isGestureMonitor,
5084 const std::string& name,
5085 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005086 std::shared_ptr<InputChannel> serverChannel;
5087 std::unique_ptr<InputChannel> clientChannel;
5088 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5089 if (result) {
5090 return base::Error(result) << "Failed to open input channel pair with name " << name;
5091 }
5092
Michael Wright3dd60e22019-03-27 22:06:44 +00005093 { // acquire lock
5094 std::scoped_lock _l(mLock);
5095
5096 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005097 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5098 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005099 }
5100
Garfield Tan15601662020-09-22 15:32:38 -07005101 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00005102
Garfield Tan15601662020-09-22 15:32:38 -07005103 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005104 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005105 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005107 auto& monitorsByDisplay =
5108 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005109 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005110
5111 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005112 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5113 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005114 }
Garfield Tan15601662020-09-22 15:32:38 -07005115
Michael Wright3dd60e22019-03-27 22:06:44 +00005116 // Wake the looper because some connections have changed.
5117 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005118 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005119}
5120
Garfield Tan15601662020-09-22 15:32:38 -07005121status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005123 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
Garfield Tan15601662020-09-22 15:32:38 -07005125 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 if (status) {
5127 return status;
5128 }
5129 } // release lock
5130
5131 // Wake the poll loop because removing the connection may have changed the current
5132 // synchronization state.
5133 mLooper->wake();
5134 return OK;
5135}
5136
Garfield Tan15601662020-09-22 15:32:38 -07005137status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5138 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005139 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005141 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 return BAD_VALUE;
5143 }
5144
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005145 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005146 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005147
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005149 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 }
5151
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005152 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153
5154 nsecs_t currentTime = now();
5155 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5156
5157 connection->status = Connection::STATUS_ZOMBIE;
5158 return OK;
5159}
5160
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005161void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5162 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5163 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005164}
5165
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005166void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005167 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005168 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005169 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005170 std::vector<Monitor>& monitors = it->second;
5171 const size_t numMonitors = monitors.size();
5172 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005173 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005174 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5175 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005176 monitors.erase(monitors.begin() + i);
5177 break;
5178 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005179 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005180 if (monitors.empty()) {
5181 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005182 } else {
5183 ++it;
5184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 }
5186}
5187
Michael Wright3dd60e22019-03-27 22:06:44 +00005188status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5189 { // acquire lock
5190 std::scoped_lock _l(mLock);
5191 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5192
5193 if (!foundDisplayId) {
5194 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5195 return BAD_VALUE;
5196 }
5197 int32_t displayId = foundDisplayId.value();
5198
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005199 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5200 mTouchStatesByDisplay.find(displayId);
5201 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005202 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5203 return BAD_VALUE;
5204 }
5205
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005206 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005207 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005208 std::optional<int32_t> foundDeviceId;
5209 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005210 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005211 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005212 foundDeviceId = state.deviceId;
5213 }
5214 }
5215 if (!foundDeviceId || !state.down) {
5216 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005217 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005218 return BAD_VALUE;
5219 }
5220 int32_t deviceId = foundDeviceId.value();
5221
5222 // Send cancel events to all the input channels we're stealing from.
5223 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005224 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005225 options.deviceId = deviceId;
5226 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005227 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005228 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005229 std::shared_ptr<InputChannel> channel =
5230 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005231 if (channel != nullptr) {
5232 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005233 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005234 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005235 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005236 canceledWindows += "]";
5237 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5238 canceledWindows.c_str());
5239
Michael Wright3dd60e22019-03-27 22:06:44 +00005240 // Then clear the current touch state so we stop dispatching to them as well.
5241 state.filterNonMonitors();
5242 }
5243 return OK;
5244}
5245
Prabir Pradhan99987712020-11-10 18:43:05 -08005246void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5247 { // acquire lock
5248 std::scoped_lock _l(mLock);
5249 if (DEBUG_FOCUS) {
5250 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5251 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5252 windowHandle != nullptr ? windowHandle->getName().c_str()
5253 : "token without window");
5254 }
5255
Vishnu Nairc519ff72021-01-21 08:23:08 -08005256 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005257 if (focusedToken != windowToken) {
5258 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5259 enabled ? "enable" : "disable");
5260 return;
5261 }
5262
5263 if (enabled == mFocusedWindowRequestedPointerCapture) {
5264 ALOGW("Ignoring request to %s Pointer Capture: "
5265 "window has %s requested pointer capture.",
5266 enabled ? "enable" : "disable", enabled ? "already" : "not");
5267 return;
5268 }
5269
5270 mFocusedWindowRequestedPointerCapture = enabled;
5271 setPointerCaptureLocked(enabled);
5272 } // release lock
5273
5274 // Wake the thread to process command entries.
5275 mLooper->wake();
5276}
5277
Michael Wright3dd60e22019-03-27 22:06:44 +00005278std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5279 const sp<IBinder>& token) {
5280 for (const auto& it : mGestureMonitorsByDisplay) {
5281 const std::vector<Monitor>& monitors = it.second;
5282 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005283 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005284 return it.first;
5285 }
5286 }
5287 }
5288 return std::nullopt;
5289}
5290
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005291std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5292 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5293 if (gesturePid.has_value()) {
5294 return gesturePid;
5295 }
5296 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5297}
5298
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005299sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005300 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005301 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005302 }
5303
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005304 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005305 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005306 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005307 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 }
5309 }
Robert Carr4e670e52018-08-15 13:26:12 -07005310
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005311 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312}
5313
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005314std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5315 sp<Connection> connection = getConnectionLocked(connectionToken);
5316 if (connection == nullptr) {
5317 return "<nullptr>";
5318 }
5319 return connection->getInputChannelName();
5320}
5321
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005322void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005323 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005324 removeByValue(mConnectionsByFd, connection);
5325}
5326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005327void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5328 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005329 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005330 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5331 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 commandEntry->connection = connection;
5333 commandEntry->eventTime = currentTime;
5334 commandEntry->seq = seq;
5335 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005336 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005337 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338}
5339
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005340void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5341 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005343 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005345 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5346 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005348 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349}
5350
Vishnu Nairad321cd2020-08-20 16:40:21 -07005351void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5352 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005353 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5354 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005355 commandEntry->oldToken = oldToken;
5356 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005357 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005358}
5359
arthurhungf452d0b2021-01-06 00:19:52 +08005360void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5361 std::unique_ptr<CommandEntry> commandEntry =
5362 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5363 commandEntry->newToken = token;
5364 commandEntry->x = x;
5365 commandEntry->y = y;
5366 postCommandLocked(std::move(commandEntry));
5367}
5368
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005369void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5370 if (connection == nullptr) {
5371 LOG_ALWAYS_FATAL("Caller must check for nullness");
5372 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005373 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5374 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005375 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005376 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005377 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005378 return;
5379 }
5380 /**
5381 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5382 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5383 * has changed. This could cause newer entries to time out before the already dispatched
5384 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5385 * processes the events linearly. So providing information about the oldest entry seems to be
5386 * most useful.
5387 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005388 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005389 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5390 std::string reason =
5391 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005392 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005393 ns2ms(currentWait),
5394 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005395 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005396 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005397
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005398 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5399
5400 // Stop waking up for events on this connection, it is already unresponsive
5401 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005402}
5403
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005404void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5405 std::string reason =
5406 StringPrintf("%s does not have a focused window", application->getName().c_str());
5407 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005408
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005409 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5410 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5411 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005412 postCommandLocked(std::move(commandEntry));
5413}
5414
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005415void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5416 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5417 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5418 commandEntry->obscuringPackage = obscuringPackage;
5419 postCommandLocked(std::move(commandEntry));
5420}
5421
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005422void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5423 const std::string& reason) {
5424 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5425 updateLastAnrStateLocked(windowLabel, reason);
5426}
5427
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005428void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5429 const std::string& reason) {
5430 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005431 updateLastAnrStateLocked(windowLabel, reason);
5432}
5433
5434void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5435 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005437 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 struct tm tm;
5439 localtime_r(&t, &tm);
5440 char timestr[64];
5441 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005442 mLastAnrState.clear();
5443 mLastAnrState += INDENT "ANR:\n";
5444 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005445 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5446 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005447 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448}
5449
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005450void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 mLock.unlock();
5452
5453 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5454
5455 mLock.lock();
5456}
5457
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005458void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 sp<Connection> connection = commandEntry->connection;
5460
5461 if (connection->status != Connection::STATUS_ZOMBIE) {
5462 mLock.unlock();
5463
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005464 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465
5466 mLock.lock();
5467 }
5468}
5469
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005470void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005471 sp<IBinder> oldToken = commandEntry->oldToken;
5472 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005473 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005474 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005475 mLock.lock();
5476}
5477
arthurhungf452d0b2021-01-06 00:19:52 +08005478void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5479 sp<IBinder> newToken = commandEntry->newToken;
5480 mLock.unlock();
5481 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5482 mLock.lock();
5483}
5484
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005485void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005487
5488 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5489
5490 mLock.lock();
5491}
5492
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005493void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005494 mLock.unlock();
5495
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005496 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497
5498 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005499}
5500
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005501void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005502 mLock.unlock();
5503
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005504 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5505
5506 mLock.lock();
5507}
5508
5509void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5510 mLock.unlock();
5511
5512 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5513
5514 mLock.lock();
5515}
5516
5517void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5518 mLock.unlock();
5519
5520 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005521
5522 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005523}
5524
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005525void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5526 mLock.unlock();
5527
5528 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5529
5530 mLock.lock();
5531}
5532
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5534 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005535 KeyEntry& entry = *(commandEntry->keyEntry);
5536 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537
5538 mLock.unlock();
5539
Michael Wright2b3c3302018-03-02 17:19:13 +00005540 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005541 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005542 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005543 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5544 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005545 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547
5548 mLock.lock();
5549
5550 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005551 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005553 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005555 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5556 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558}
5559
chaviwfd6d3512019-03-25 13:23:49 -07005560void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5561 mLock.unlock();
5562 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5563 mLock.lock();
5564}
5565
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005566/**
5567 * Connection is responsive if it has no events in the waitQueue that are older than the
5568 * current time.
5569 */
5570static bool isConnectionResponsive(const Connection& connection) {
5571 const nsecs_t currentTime = now();
5572 for (const DispatchEntry* entry : connection.waitQueue) {
5573 if (entry->timeoutTime < currentTime) {
5574 return false;
5575 }
5576 }
5577 return true;
5578}
5579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005580void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005582 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005584 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585
5586 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005587 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005588 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005589 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005591 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005592 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005593 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005594 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5595 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005596 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005597 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005598
5599 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005600 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005601 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005602 restartEvent =
5603 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005604 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005605 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005606 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5607 handled);
5608 } else {
5609 restartEvent = false;
5610 }
5611
5612 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005613 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005614 // contents of the wait queue to have been drained, so we need to double-check
5615 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005616 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5617 if (dispatchEntryIt != connection->waitQueue.end()) {
5618 dispatchEntry = *dispatchEntryIt;
5619 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005620 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5621 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005622 if (!connection->responsive) {
5623 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005624 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005625 // The connection was unresponsive, and now it's responsive.
5626 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005627 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005628 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005629 traceWaitQueueLength(connection);
5630 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005631 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005632 traceOutboundQueueLength(connection);
5633 } else {
5634 releaseDispatchEntry(dispatchEntry);
5635 }
5636 }
5637
5638 // Start the next dispatch cycle for this connection.
5639 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640}
5641
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005642void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5643 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5644 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5645 monitorUnresponsiveCommand->pid = pid;
5646 monitorUnresponsiveCommand->reason = std::move(reason);
5647 postCommandLocked(std::move(monitorUnresponsiveCommand));
5648}
5649
5650void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5651 std::string reason) {
5652 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5653 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5654 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5655 windowUnresponsiveCommand->reason = std::move(reason);
5656 postCommandLocked(std::move(windowUnresponsiveCommand));
5657}
5658
5659void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5660 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5661 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5662 monitorResponsiveCommand->pid = pid;
5663 postCommandLocked(std::move(monitorResponsiveCommand));
5664}
5665
5666void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5667 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5668 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5669 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5670 postCommandLocked(std::move(windowResponsiveCommand));
5671}
5672
5673/**
5674 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5675 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5676 * command entry to the command queue.
5677 */
5678void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5679 std::string reason) {
5680 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5681 if (connection.monitor) {
5682 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5683 reason.c_str());
5684 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5685 if (!pid.has_value()) {
5686 ALOGE("Could not find unresponsive monitor for connection %s",
5687 connection.inputChannel->getName().c_str());
5688 return;
5689 }
5690 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5691 return;
5692 }
5693 // If not a monitor, must be a window
5694 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5695 reason.c_str());
5696 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5697}
5698
5699/**
5700 * Tell the policy that a connection has become responsive so that it can stop ANR.
5701 */
5702void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5703 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5704 if (connection.monitor) {
5705 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5706 if (!pid.has_value()) {
5707 ALOGE("Could not find responsive monitor for connection %s",
5708 connection.inputChannel->getName().c_str());
5709 return;
5710 }
5711 sendMonitorResponsiveCommandLocked(pid.value());
5712 return;
5713 }
5714 // If not a monitor, must be a window
5715 sendWindowResponsiveCommandLocked(connectionToken);
5716}
5717
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005719 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005720 KeyEntry& keyEntry, bool handled) {
5721 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005722 if (!handled) {
5723 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005724 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005725 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005726 return false;
5727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005729 // Get the fallback key state.
5730 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005731 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005732 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005733 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005734 connection->inputState.removeFallbackKey(originalKeyCode);
5735 }
5736
5737 if (handled || !dispatchEntry->hasForegroundTarget()) {
5738 // If the application handles the original key for which we previously
5739 // generated a fallback or if the window is not a foreground window,
5740 // then cancel the associated fallback key, if any.
5741 if (fallbackKeyCode != -1) {
5742 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005744 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005745 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005746 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005748 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005749 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750
5751 mLock.unlock();
5752
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005753 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005754 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755
5756 mLock.lock();
5757
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005758 // Cancel the fallback key.
5759 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005761 "application handled the original non-fallback key "
5762 "or is no longer a foreground target, "
5763 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 options.keyCode = fallbackKeyCode;
5765 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005767 connection->inputState.removeFallbackKey(originalKeyCode);
5768 }
5769 } else {
5770 // If the application did not handle a non-fallback key, first check
5771 // that we are in a good state to perform unhandled key event processing
5772 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005773 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005774 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005776 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005777 "since this is not an initial down. "
5778 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005779 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005781 return false;
5782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005784 // Dispatch the unhandled key to the policy.
5785#if DEBUG_OUTBOUND_EVENT_DETAILS
5786 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005787 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005788 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005789#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005790 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005791
5792 mLock.unlock();
5793
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005794 bool fallback =
5795 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005796 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005797
5798 mLock.lock();
5799
5800 if (connection->status != Connection::STATUS_NORMAL) {
5801 connection->inputState.removeFallbackKey(originalKeyCode);
5802 return false;
5803 }
5804
5805 // Latch the fallback keycode for this key on an initial down.
5806 // The fallback keycode cannot change at any other point in the lifecycle.
5807 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005809 fallbackKeyCode = event.getKeyCode();
5810 } else {
5811 fallbackKeyCode = AKEYCODE_UNKNOWN;
5812 }
5813 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5814 }
5815
5816 ALOG_ASSERT(fallbackKeyCode != -1);
5817
5818 // Cancel the fallback key if the policy decides not to send it anymore.
5819 // We will continue to dispatch the key to the policy but we will no
5820 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005821 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5822 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005823#if DEBUG_OUTBOUND_EVENT_DETAILS
5824 if (fallback) {
5825 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005826 "as a fallback for %d, but on the DOWN it had requested "
5827 "to send %d instead. Fallback canceled.",
5828 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005829 } else {
5830 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005831 "but on the DOWN it had requested to send %d. "
5832 "Fallback canceled.",
5833 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005834 }
5835#endif
5836
5837 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5838 "canceling fallback, policy no longer desires it");
5839 options.keyCode = fallbackKeyCode;
5840 synthesizeCancelationEventsForConnectionLocked(connection, options);
5841
5842 fallback = false;
5843 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005844 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005845 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005846 }
5847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848
5849#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005850 {
5851 std::string msg;
5852 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5853 connection->inputState.getFallbackKeys();
5854 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005855 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005857 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005858 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005859 }
5860#endif
5861
5862 if (fallback) {
5863 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005864 keyEntry.eventTime = event.getEventTime();
5865 keyEntry.deviceId = event.getDeviceId();
5866 keyEntry.source = event.getSource();
5867 keyEntry.displayId = event.getDisplayId();
5868 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5869 keyEntry.keyCode = fallbackKeyCode;
5870 keyEntry.scanCode = event.getScanCode();
5871 keyEntry.metaState = event.getMetaState();
5872 keyEntry.repeatCount = event.getRepeatCount();
5873 keyEntry.downTime = event.getDownTime();
5874 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005875
5876#if DEBUG_OUTBOUND_EVENT_DETAILS
5877 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005878 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005879 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880#endif
5881 return true; // restart the event
5882 } else {
5883#if DEBUG_OUTBOUND_EVENT_DETAILS
5884 ALOGD("Unhandled key event: No fallback key.");
5885#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005886
5887 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005888 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889 }
5890 }
5891 return false;
5892}
5893
5894bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005895 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005896 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 return false;
5898}
5899
5900void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5901 mLock.unlock();
5902
Sean Stoutb4e0a592021-02-23 07:34:53 -08005903 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
5904 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905
5906 mLock.lock();
5907}
5908
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005909void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5910 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911 // TODO Write some statistics about how long we spend waiting.
5912}
5913
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005914/**
5915 * Report the touch event latency to the statsd server.
5916 * Input events are reported for statistics if:
5917 * - This is a touchscreen event
5918 * - InputFilter is not enabled
5919 * - Event is not injected or synthesized
5920 *
5921 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5922 * from getting aggregated with the "old" data.
5923 */
5924void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5925 REQUIRES(mLock) {
5926 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5927 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5928 if (!reportForStatistics) {
5929 return;
5930 }
5931
5932 if (mTouchStatistics.shouldReport()) {
5933 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5934 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5935 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5936 mTouchStatistics.reset();
5937 }
5938 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5939 mTouchStatistics.addValue(latencyMicros);
5940}
5941
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942void InputDispatcher::traceInboundQueueLengthLocked() {
5943 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005944 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 }
5946}
5947
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005948void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 if (ATRACE_ENABLED()) {
5950 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005951 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005952 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953 }
5954}
5955
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005956void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957 if (ATRACE_ENABLED()) {
5958 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005959 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005960 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 }
5962}
5963
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005964void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005965 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005967 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968 dumpDispatchStateLocked(dump);
5969
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005970 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005971 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005972 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 }
5974}
5975
5976void InputDispatcher::monitor() {
5977 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005978 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005980 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981}
5982
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005983/**
5984 * Wake up the dispatcher and wait until it processes all events and commands.
5985 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5986 * this method can be safely called from any thread, as long as you've ensured that
5987 * the work you are interested in completing has already been queued.
5988 */
5989bool InputDispatcher::waitForIdle() {
5990 /**
5991 * Timeout should represent the longest possible time that a device might spend processing
5992 * events and commands.
5993 */
5994 constexpr std::chrono::duration TIMEOUT = 100ms;
5995 std::unique_lock lock(mLock);
5996 mLooper->wake();
5997 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5998 return result == std::cv_status::no_timeout;
5999}
6000
Vishnu Naire798b472020-07-23 13:52:21 -07006001/**
6002 * Sets focus to the window identified by the token. This must be called
6003 * after updating any input window handles.
6004 *
6005 * Params:
6006 * request.token - input channel token used to identify the window that should gain focus.
6007 * request.focusedToken - the token that the caller expects currently to be focused. If the
6008 * specified token does not match the currently focused window, this request will be dropped.
6009 * If the specified focused token matches the currently focused window, the call will succeed.
6010 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6011 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6012 * when requesting the focus change. This determines which request gets
6013 * precedence if there is a focus change request from another source such as pointer down.
6014 */
Vishnu Nair958da932020-08-21 17:12:37 -07006015void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6016 { // acquire lock
6017 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006018 std::optional<FocusResolver::FocusChanges> changes =
6019 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6020 if (changes) {
6021 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006022 }
6023 } // release lock
6024 // Wake up poll loop since it may need to make new input dispatching choices.
6025 mLooper->wake();
6026}
6027
Vishnu Nairc519ff72021-01-21 08:23:08 -08006028void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6029 if (changes.oldFocus) {
6030 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006031 if (focusedInputChannel) {
6032 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6033 "focus left window");
6034 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006035 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006036 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006037 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006038 if (changes.newFocus) {
6039 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006040 }
6041
Prabir Pradhan99987712020-11-10 18:43:05 -08006042 // If a window has pointer capture, then it must have focus. We need to ensure that this
6043 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6044 // If the window loses focus before it loses pointer capture, then the window can be in a state
6045 // where it has pointer capture but not focus, violating the contract. Therefore we must
6046 // dispatch the pointer capture event before the focus event. Since focus events are added to
6047 // the front of the queue (above), we add the pointer capture event to the front of the queue
6048 // after the focus events are added. This ensures the pointer capture event ends up at the
6049 // front.
6050 disablePointerCaptureForcedLocked();
6051
Vishnu Nairc519ff72021-01-21 08:23:08 -08006052 if (mFocusedDisplayId == changes.displayId) {
6053 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006054 }
6055}
Vishnu Nair958da932020-08-21 17:12:37 -07006056
Prabir Pradhan99987712020-11-10 18:43:05 -08006057void InputDispatcher::disablePointerCaptureForcedLocked() {
6058 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6059 return;
6060 }
6061
6062 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6063
6064 if (mFocusedWindowRequestedPointerCapture) {
6065 mFocusedWindowRequestedPointerCapture = false;
6066 setPointerCaptureLocked(false);
6067 }
6068
6069 if (!mWindowTokenWithPointerCapture) {
6070 // No need to send capture changes because no window has capture.
6071 return;
6072 }
6073
6074 if (mPendingEvent != nullptr) {
6075 // Move the pending event to the front of the queue. This will give the chance
6076 // for the pending event to be dropped if it is a captured event.
6077 mInboundQueue.push_front(mPendingEvent);
6078 mPendingEvent = nullptr;
6079 }
6080
6081 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6082 false /* hasCapture */);
6083 mInboundQueue.push_front(std::move(entry));
6084}
6085
Prabir Pradhan99987712020-11-10 18:43:05 -08006086void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6087 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6088 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6089 commandEntry->enabled = enabled;
6090 postCommandLocked(std::move(commandEntry));
6091}
6092
6093void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6094 android::inputdispatcher::CommandEntry* commandEntry) {
6095 mLock.unlock();
6096
6097 mPolicy->setPointerCapture(commandEntry->enabled);
6098
6099 mLock.lock();
6100}
6101
Garfield Tane84e6f92019-08-29 17:28:41 -07006102} // namespace android::inputdispatcher