blob: 07b4f308747804502149564f39bbf0223754d9e0 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -070050#include <InputFlingerProperties.sysprop.h>
Michael Wright2b3c3302018-03-02 17:19:13 +000051#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080052#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050054#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070055#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100056#include <binder/IServiceManager.h>
57#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080058#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080081using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000082using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080083using android::base::StringPrintf;
chaviw98318de2021-05-19 16:45:23 -050084using android::gui::FocusRequest;
85using android::gui::TouchOcclusionMode;
86using android::gui::WindowInfo;
87using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080088using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100089using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080090using android::os::InputEventInjectionResult;
91using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100092using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080093
Garfield Tane84e6f92019-08-29 17:28:41 -070094namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Prabir Pradhan93a0f912021-04-21 13:47:42 -070096// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
97// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
98static bool isPerWindowInputRotationEnabled() {
99 static const bool PER_WINDOW_INPUT_ROTATION =
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700100 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
101
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700102 return PER_WINDOW_INPUT_ROTATION;
103}
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Default input dispatching timeout if there is no focused application or paused window
106// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800107const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
108 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
109 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
111// Amount of time to allow for all pending events to be processed when an app switch
112// key is on the way. This is used to preempt input dispatch and drop input events
113// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000114constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115
116// Amount of time to allow for an event to be dispatched (measured since its eventTime)
117// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000118constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000121constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
122
123// Log a warning when an interception call takes longer than this to process.
124constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700126// Additional key latency in case a connection is still processing some motion events.
127// This will help with the case when a user touched a button that opens a new window,
128// and gives us the chance to dispatch the key to this new window.
129constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
130
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000132constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
133
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000134// Event log tags. See EventLogTags.logtags for reference
135constexpr int LOGTAG_INPUT_INTERACTION = 62000;
136constexpr int LOGTAG_INPUT_FOCUS = 62001;
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138static inline nsecs_t now() {
139 return systemTime(SYSTEM_TIME_MONOTONIC);
140}
141
142static inline const char* toString(bool value) {
143 return value ? "true" : "false";
144}
145
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000146static inline const std::string toString(sp<IBinder> binder) {
147 if (binder == nullptr) {
148 return "<null>";
149 }
150 return StringPrintf("%p", binder.get());
151}
152
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
155 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156}
157
158static bool isValidKeyAction(int32_t action) {
159 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 case AKEY_EVENT_ACTION_DOWN:
161 case AKEY_EVENT_ACTION_UP:
162 return true;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
168static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170 ALOGE("Key event has invalid action code 0x%x", action);
171 return false;
172 }
173 return true;
174}
175
Michael Wright7b159c92015-05-14 14:48:03 +0100176static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_DOWN:
179 case AMOTION_EVENT_ACTION_UP:
180 case AMOTION_EVENT_ACTION_CANCEL:
181 case AMOTION_EVENT_ACTION_MOVE:
182 case AMOTION_EVENT_ACTION_OUTSIDE:
183 case AMOTION_EVENT_ACTION_HOVER_ENTER:
184 case AMOTION_EVENT_ACTION_HOVER_MOVE:
185 case AMOTION_EVENT_ACTION_HOVER_EXIT:
186 case AMOTION_EVENT_ACTION_SCROLL:
187 return true;
188 case AMOTION_EVENT_ACTION_POINTER_DOWN:
189 case AMOTION_EVENT_ACTION_POINTER_UP: {
190 int32_t index = getMotionEventActionPointerIndex(action);
191 return index >= 0 && index < pointerCount;
192 }
193 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
194 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
195 return actionButton != 0;
196 default:
197 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 }
199}
200
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500201static int64_t millis(std::chrono::nanoseconds t) {
202 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
203}
204
Michael Wright7b159c92015-05-14 14:48:03 +0100205static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700206 const PointerProperties* pointerProperties) {
207 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 ALOGE("Motion event has invalid action code 0x%x", action);
209 return false;
210 }
211 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000212 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700213 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 return false;
215 }
216 BitSet32 pointerIdBits;
217 for (size_t i = 0; i < pointerCount; i++) {
218 int32_t id = pointerProperties[i].id;
219 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700220 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
221 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return false;
223 }
224 if (pointerIdBits.hasBit(id)) {
225 ALOGE("Motion event has duplicate pointer id %d", id);
226 return false;
227 }
228 pointerIdBits.markBit(id);
229 }
230 return true;
231}
232
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000233static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000235 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 }
237
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000238 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 bool first = true;
240 Region::const_iterator cur = region.begin();
241 Region::const_iterator const tail = region.end();
242 while (cur != tail) {
243 if (first) {
244 first = false;
245 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800246 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800248 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 cur++;
250 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000251 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252}
253
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500254static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
255 constexpr size_t maxEntries = 50; // max events to print
256 constexpr size_t skipBegin = maxEntries / 2;
257 const size_t skipEnd = queue.size() - maxEntries / 2;
258 // skip from maxEntries / 2 ... size() - maxEntries/2
259 // only print from 0 .. skipBegin and then from skipEnd .. size()
260
261 std::string dump;
262 for (size_t i = 0; i < queue.size(); i++) {
263 const DispatchEntry& entry = *queue[i];
264 if (i >= skipBegin && i < skipEnd) {
265 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
266 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
267 continue;
268 }
269 dump.append(INDENT4);
270 dump += entry.eventEntry->getDescription();
271 dump += StringPrintf(", seq=%" PRIu32
272 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
273 entry.seq, entry.targetFlags, entry.resolvedAction,
274 ns2ms(currentTime - entry.eventEntry->eventTime));
275 if (entry.deliveryTime != 0) {
276 // This entry was delivered, so add information on how long we've been waiting
277 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
278 }
279 dump.append("\n");
280 }
281 return dump;
282}
283
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700284/**
285 * Find the entry in std::unordered_map by key, and return it.
286 * If the entry is not found, return a default constructed entry.
287 *
288 * Useful when the entries are vectors, since an empty vector will be returned
289 * if the entry is not found.
290 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
291 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700292template <typename K, typename V>
293static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700294 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700295 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800296}
297
chaviw98318de2021-05-19 16:45:23 -0500298static bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700299 if (first == second) {
300 return true;
301 }
302
303 if (first == nullptr || second == nullptr) {
304 return false;
305 }
306
307 return first->getToken() == second->getToken();
308}
309
chaviw98318de2021-05-19 16:45:23 -0500310static bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000311 if (first == nullptr || second == nullptr) {
312 return false;
313 }
314 return first->applicationInfo.token != nullptr &&
315 first->applicationInfo.token == second->applicationInfo.token;
316}
317
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800318static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
319 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
320}
321
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000322static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700323 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000324 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900325 if (eventEntry->type == EventEntry::Type::MOTION) {
326 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700327 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
328 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900329 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700330 // Use identity transform for joystick and position-based (touchpad) events because they
331 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900332 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700333 1.0f /*globalScaleFactor*/,
Evan Rosky09576692021-07-01 12:22:09 -0700334 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700335 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900336 }
337 }
338
chaviw1ff3d1e2020-07-01 15:53:47 -0700339 if (inputTarget.useDefaultPointerTransform()) {
340 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700341 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700342 inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700343 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700344 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345 }
346
347 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
348 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700350 std::vector<PointerCoords> pointerCoords;
351 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352
353 // Use the first pointer information to normalize all other pointers. This could be any pointer
354 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 // uses the transform for the normalized pointer.
356 const ui::Transform& firstPointerTransform =
357 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
358 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 // Iterate through all pointers in the event to normalize against the first.
361 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
362 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
363 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700364 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 // First, apply the current pointer's transform to update the coordinates into
368 // window space.
369 pointerCoords[pointerIndex].transform(currTransform);
370 // Next, apply the inverse transform of the normalized coordinates so the
371 // current coordinates are transformed into the normalized coordinate space.
372 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000373 }
374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700375 std::unique_ptr<MotionEntry> combinedMotionEntry =
376 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
377 motionEntry.deviceId, motionEntry.source,
378 motionEntry.displayId, motionEntry.policyFlags,
379 motionEntry.action, motionEntry.actionButton,
380 motionEntry.flags, motionEntry.metaState,
381 motionEntry.buttonState, motionEntry.classification,
382 motionEntry.edgeFlags, motionEntry.xPrecision,
383 motionEntry.yPrecision, motionEntry.xCursorPosition,
384 motionEntry.yCursorPosition, motionEntry.downTime,
385 motionEntry.pointerCount, motionEntry.pointerProperties,
386 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387
388 if (motionEntry.injectionState) {
389 combinedMotionEntry->injectionState = motionEntry.injectionState;
390 combinedMotionEntry->injectionState->refCount += 1;
391 }
392
393 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700394 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700395 firstPointerTransform, inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700396 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700397 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398 return dispatchEntry;
399}
400
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700401static void addGestureMonitors(const std::vector<Monitor>& monitors,
402 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
403 float yOffset = 0) {
404 if (monitors.empty()) {
405 return;
406 }
407 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
408 for (const Monitor& monitor : monitors) {
409 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
410 }
411}
412
Garfield Tan15601662020-09-22 15:32:38 -0700413static status_t openInputChannelPair(const std::string& name,
414 std::shared_ptr<InputChannel>& serverChannel,
415 std::unique_ptr<InputChannel>& clientChannel) {
416 std::unique_ptr<InputChannel> uniqueServerChannel;
417 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
418
419 serverChannel = std::move(uniqueServerChannel);
420 return result;
421}
422
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500423template <typename T>
424static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
425 if (lhs == nullptr && rhs == nullptr) {
426 return true;
427 }
428 if (lhs == nullptr || rhs == nullptr) {
429 return false;
430 }
431 return *lhs == *rhs;
432}
433
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000434static sp<IPlatformCompatNative> getCompatService() {
435 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
436 if (service == nullptr) {
437 ALOGE("Failed to link to compat service");
438 return nullptr;
439 }
440 return interface_cast<IPlatformCompatNative>(service);
441}
442
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000443static KeyEvent createKeyEvent(const KeyEntry& entry) {
444 KeyEvent event;
445 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
446 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
447 entry.repeatCount, entry.downTime, entry.eventTime);
448 return event;
449}
450
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000451static std::optional<int32_t> findMonitorPidByToken(
452 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
453 const sp<IBinder>& token) {
454 for (const auto& it : monitorsByDisplay) {
455 const std::vector<Monitor>& monitors = it.second;
456 for (const Monitor& monitor : monitors) {
457 if (monitor.inputChannel->getConnectionToken() == token) {
458 return monitor.pid;
459 }
460 }
461 }
462 return std::nullopt;
463}
464
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000465static bool shouldReportMetricsForConnection(const Connection& connection) {
466 // Do not keep track of gesture monitors. They receive every event and would disproportionately
467 // affect the statistics.
468 if (connection.monitor) {
469 return false;
470 }
471 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
472 if (!connection.responsive) {
473 return false;
474 }
475 return true;
476}
477
478static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
479 const Connection& connection) {
480 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
481 const int32_t& inputEventId = eventEntry.id;
482 if (inputEventId != dispatchEntry.resolvedEventId) {
483 // Event was transmuted
484 return false;
485 }
486 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
487 return false;
488 }
489 // Only track latency for events that originated from hardware
490 if (eventEntry.isSynthesized()) {
491 return false;
492 }
493 const EventEntry::Type& inputEventEntryType = eventEntry.type;
494 if (inputEventEntryType == EventEntry::Type::KEY) {
495 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
496 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
497 return false;
498 }
499 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
500 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
501 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
502 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
503 return false;
504 }
505 } else {
506 // Not a key or a motion
507 return false;
508 }
509 if (!shouldReportMetricsForConnection(connection)) {
510 return false;
511 }
512 return true;
513}
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515// --- InputDispatcher ---
516
Garfield Tan00f511d2019-06-12 16:55:40 -0700517InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
518 : mPolicy(policy),
519 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700520 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800521 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700522 mAppSwitchSawKeyDown(false),
523 mAppSwitchDueTime(LONG_LONG_MAX),
524 mNextUnblockedEvent(nullptr),
525 mDispatchEnabled(false),
526 mDispatchFrozen(false),
527 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800528 // mInTouchMode will be initialized by the WindowManager to the default device config.
529 // To avoid leaking stack in case that call never comes, and for tests,
530 // initialize it here anyways.
531 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100532 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000533 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800534 mFocusedWindowRequestedPointerCapture(false),
535 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000536 mLatencyAggregator(),
537 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000538 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800540 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541
Yi Kong9b14ac62018-07-17 13:48:38 -0700542 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543
544 policy->getDispatcherConfiguration(&mConfig);
545}
546
547InputDispatcher::~InputDispatcher() {
548 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800549 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550
551 resetKeyRepeatLocked();
552 releasePendingEventLocked();
553 drainInboundQueueLocked();
554 }
555
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000556 while (!mConnectionsByToken.empty()) {
557 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700558 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 }
560}
561
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700562status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700563 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700564 return ALREADY_EXISTS;
565 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700566 mThread = std::make_unique<InputThread>(
567 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
568 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700569}
570
571status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700572 if (mThread && mThread->isCallingThread()) {
573 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700574 return INVALID_OPERATION;
575 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700576 mThread.reset();
577 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700578}
579
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580void InputDispatcher::dispatchOnce() {
581 nsecs_t nextWakeupTime = LONG_LONG_MAX;
582 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800583 std::scoped_lock _l(mLock);
584 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585
586 // Run a dispatch loop if there are no pending commands.
587 // The dispatch loop might enqueue commands to run afterwards.
588 if (!haveCommandsLocked()) {
589 dispatchOnceInnerLocked(&nextWakeupTime);
590 }
591
592 // Run all pending commands if there are any.
593 // If any commands were run then force the next poll to wake up immediately.
594 if (runCommandsLockedInterruptible()) {
595 nextWakeupTime = LONG_LONG_MIN;
596 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800597
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700598 // If we are still waiting for ack on some events,
599 // we might have to wake up earlier to check if an app is anr'ing.
600 const nsecs_t nextAnrCheck = processAnrsLocked();
601 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
602
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800603 // We are about to enter an infinitely long sleep, because we have no commands or
604 // pending or queued events
605 if (nextWakeupTime == LONG_LONG_MAX) {
606 mDispatcherEnteredIdle.notify_all();
607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 } // release lock
609
610 // Wait for callback or timeout or wake. (make sure we round up, not down)
611 nsecs_t currentTime = now();
612 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
613 mLooper->pollOnce(timeoutMillis);
614}
615
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700616/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500617 * Raise ANR if there is no focused window.
618 * Before the ANR is raised, do a final state check:
619 * 1. The currently focused application must be the same one we are waiting for.
620 * 2. Ensure we still don't have a focused window.
621 */
622void InputDispatcher::processNoFocusedWindowAnrLocked() {
623 // Check if the application that we are waiting for is still focused.
624 std::shared_ptr<InputApplicationHandle> focusedApplication =
625 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
626 if (focusedApplication == nullptr ||
627 focusedApplication->getApplicationToken() !=
628 mAwaitedFocusedApplication->getApplicationToken()) {
629 // Unexpected because we should have reset the ANR timer when focused application changed
630 ALOGE("Waited for a focused window, but focused application has already changed to %s",
631 focusedApplication->getName().c_str());
632 return; // The focused application has changed.
633 }
634
chaviw98318de2021-05-19 16:45:23 -0500635 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500636 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
637 if (focusedWindowHandle != nullptr) {
638 return; // We now have a focused window. No need for ANR.
639 }
640 onAnrLocked(mAwaitedFocusedApplication);
641}
642
643/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700644 * Check if any of the connections' wait queues have events that are too old.
645 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
646 * Return the time at which we should wake up next.
647 */
648nsecs_t InputDispatcher::processAnrsLocked() {
649 const nsecs_t currentTime = now();
650 nsecs_t nextAnrCheck = LONG_LONG_MAX;
651 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
652 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
653 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500654 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700655 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500656 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700657 return LONG_LONG_MIN;
658 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500659 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700660 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
661 }
662 }
663
664 // Check if any connection ANRs are due
665 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
666 if (currentTime < nextAnrCheck) { // most likely scenario
667 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
668 }
669
670 // If we reached here, we have an unresponsive connection.
671 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
672 if (connection == nullptr) {
673 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
674 return nextAnrCheck;
675 }
676 connection->responsive = false;
677 // Stop waking up for this unresponsive connection
678 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000679 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700680 return LONG_LONG_MIN;
681}
682
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500683std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500684 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700685 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500686 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700687 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500688 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689}
690
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
692 nsecs_t currentTime = now();
693
Jeff Browndc5992e2014-04-11 01:27:26 -0700694 // Reset the key repeat timer whenever normal dispatch is suspended while the
695 // device is in a non-interactive state. This is to ensure that we abort a key
696 // repeat if the device is just coming out of sleep.
697 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 resetKeyRepeatLocked();
699 }
700
701 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
702 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100703 if (DEBUG_FOCUS) {
704 ALOGD("Dispatch frozen. Waiting some more.");
705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 return;
707 }
708
709 // Optimize latency of app switches.
710 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
711 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
712 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
713 if (mAppSwitchDueTime < *nextWakeupTime) {
714 *nextWakeupTime = mAppSwitchDueTime;
715 }
716
717 // Ready to start a new event.
718 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700719 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700720 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 if (isAppSwitchDue) {
722 // The inbound queue is empty so the app switch key we were waiting
723 // for will never arrive. Stop waiting for it.
724 resetPendingAppSwitchLocked(false);
725 isAppSwitchDue = false;
726 }
727
728 // Synthesize a key repeat if appropriate.
729 if (mKeyRepeatState.lastKeyEntry) {
730 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
731 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
732 } else {
733 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
734 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
735 }
736 }
737 }
738
739 // Nothing to do if there is no pending event.
740 if (!mPendingEvent) {
741 return;
742 }
743 } else {
744 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700745 mPendingEvent = mInboundQueue.front();
746 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 traceInboundQueueLengthLocked();
748 }
749
750 // Poke user activity for this event.
751 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700752 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 }
755
756 // Now we have an event to dispatch.
757 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700758 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700760 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700762 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700764 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 }
766
767 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700768 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 }
770
771 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700773 const ConfigurationChangedEntry& typedEntry =
774 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700776 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700780 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700781 const DeviceResetEntry& typedEntry =
782 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700783 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700784 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 break;
786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100788 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700789 std::shared_ptr<FocusEntry> typedEntry =
790 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100791 dispatchFocusLocked(currentTime, typedEntry);
792 done = true;
793 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
794 break;
795 }
796
Prabir Pradhan99987712020-11-10 18:43:05 -0800797 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
798 const auto typedEntry =
799 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
800 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
801 done = true;
802 break;
803 }
804
arthurhungb89ccb02020-12-30 16:19:01 +0800805 case EventEntry::Type::DRAG: {
806 std::shared_ptr<DragEntry> typedEntry =
807 std::static_pointer_cast<DragEntry>(mPendingEvent);
808 dispatchDragLocked(currentTime, typedEntry);
809 done = true;
810 break;
811 }
812
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700813 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700814 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700816 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 resetPendingAppSwitchLocked(true);
818 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700819 } else if (dropReason == DropReason::NOT_DROPPED) {
820 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700821 }
822 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700824 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700826 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
827 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700829 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 break;
831 }
832
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700833 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700834 std::shared_ptr<MotionEntry> motionEntry =
835 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700836 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
837 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700840 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700841 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700842 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
843 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700844 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700845 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 }
Chris Yef59a2f42020-10-16 12:55:26 -0700848
849 case EventEntry::Type::SENSOR: {
850 std::shared_ptr<SensorEntry> sensorEntry =
851 std::static_pointer_cast<SensorEntry>(mPendingEvent);
852 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
853 dropReason = DropReason::APP_SWITCH;
854 }
855 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
856 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
857 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
858 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
859 dropReason = DropReason::STALE;
860 }
861 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
862 done = true;
863 break;
864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
866
867 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700869 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
Michael Wright3a981722015-06-10 15:26:13 +0100871 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872
873 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
876}
877
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700878/**
879 * Return true if the events preceding this incoming motion event should be dropped
880 * Return false otherwise (the default behaviour)
881 */
882bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700883 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700884 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700885
886 // Optimize case where the current application is unresponsive and the user
887 // decides to touch a window in a different application.
888 // If the application takes too long to catch up then we drop all events preceding
889 // the touch into the other window.
890 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700891 int32_t displayId = motionEntry.displayId;
892 int32_t x = static_cast<int32_t>(
893 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
894 int32_t y = static_cast<int32_t>(
895 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500896 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700897 findTouchedWindowAtLocked(displayId, x, y, nullptr);
898 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 touchedWindowHandle->getApplicationToken() !=
900 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700901 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700902 ALOGI("Pruning input queue because user touched a different application while waiting "
903 "for %s",
904 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700905 return true;
906 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907
908 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600909 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700910 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
911 sp<Connection> connection =
912 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000913 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 // This monitor could take more input. Drop all events preceding this
915 // event, so that gesture monitor could get a chance to receive the stream
916 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
917 "responsive gesture monitor that may handle the event",
918 mAwaitedFocusedApplication->getName().c_str());
919 return true;
920 }
921 }
922 }
923
924 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
925 // yet been processed by some connections, the dispatcher will wait for these motion
926 // events to be processed before dispatching the key event. This is because these motion events
927 // may cause a new window to be launched, which the user might expect to receive focus.
928 // To prevent waiting forever for such events, just send the key to the currently focused window
929 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
930 ALOGD("Received a new pointer down event, stop waiting for events to process and "
931 "just send the pending key event to the focused window.");
932 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700933 }
934 return false;
935}
936
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700937bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700938 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700939 mInboundQueue.push_back(std::move(newEntry));
940 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 traceInboundQueueLengthLocked();
942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700943 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700944 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 // Optimize app switch latency.
946 // If the application takes too long to catch up then we drop all events preceding
947 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700948 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700950 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700952 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700957 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700958 mAppSwitchSawKeyDown = false;
959 needWake = true;
960 }
961 }
962 }
963 break;
964 }
965
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700966 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
968 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700969 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100973 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700974 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
975 break;
976 }
977 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800978 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700979 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800980 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
981 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700982 // nothing to do
983 break;
984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 }
986
987 return needWake;
988}
989
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700991 // Do not store sensor event in recent queue to avoid flooding the queue.
992 if (entry->type != EventEntry::Type::SENSOR) {
993 mRecentQueue.push_back(entry);
994 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700995 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700996 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
998}
999
chaviw98318de2021-05-19 16:45:23 -05001000sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1001 int32_t y, TouchState* touchState,
1002 bool addOutsideTargets,
1003 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001004 if (addOutsideTargets && touchState == nullptr) {
1005 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001008 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1009 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001010 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001011 continue;
1012 }
chaviw98318de2021-05-19 16:45:23 -05001013 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001015 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016
1017 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001018 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1019 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1020 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1022 // Found window.
1023 return windowHandle;
1024 }
1025 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001026
chaviw98318de2021-05-19 16:45:23 -05001027 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001028 touchState->addOrUpdateWindow(windowHandle,
1029 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1030 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 }
1034 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001035 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036}
1037
Garfield Tane84e6f92019-08-29 17:28:41 -07001038std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001039 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001040 std::vector<TouchedMonitor> touchedMonitors;
1041
1042 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1043 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001044 return touchedMonitors;
1045}
1046
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001047void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 const char* reason;
1049 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 reason = "inbound event was dropped because the policy consumed it";
1055 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001056 case DropReason::DISABLED:
1057 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 ALOGI("Dropped event because input dispatch is disabled.");
1059 }
1060 reason = "inbound event was dropped because input dispatch is disabled";
1061 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001062 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001063 ALOGI("Dropped event because of pending overdue app switch.");
1064 reason = "inbound event was dropped because of pending overdue app switch";
1065 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 ALOGI("Dropped event because the current application is not responding and the user "
1068 "has started interacting with a different application.");
1069 reason = "inbound event was dropped because the current application is not responding "
1070 "and the user has started interacting with a different application";
1071 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 ALOGI("Dropped event because it is stale.");
1074 reason = "inbound event was dropped because it is stale";
1075 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001076 case DropReason::NO_POINTER_CAPTURE:
1077 ALOGI("Dropped event because there is no window with Pointer Capture.");
1078 reason = "inbound event was dropped because there is no window with Pointer Capture";
1079 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001080 case DropReason::NOT_DROPPED: {
1081 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001086 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001087 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1089 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001092 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001093 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1094 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1096 synthesizeCancelationEventsForAllConnectionsLocked(options);
1097 } else {
1098 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1099 synthesizeCancelationEventsForAllConnectionsLocked(options);
1100 }
1101 break;
1102 }
Chris Yef59a2f42020-10-16 12:55:26 -07001103 case EventEntry::Type::SENSOR: {
1104 break;
1105 }
arthurhungb89ccb02020-12-30 16:19:01 +08001106 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1107 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001108 break;
1109 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001110 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001111 case EventEntry::Type::CONFIGURATION_CHANGED:
1112 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001113 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001114 break;
1115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 }
1117}
1118
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001119static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1121 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122}
1123
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1125 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1126 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1127 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128}
1129
1130bool InputDispatcher::isAppSwitchPendingLocked() {
1131 return mAppSwitchDueTime != LONG_LONG_MAX;
1132}
1133
1134void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1135 mAppSwitchDueTime = LONG_LONG_MAX;
1136
1137#if DEBUG_APP_SWITCH
1138 if (handled) {
1139 ALOGD("App switch has arrived.");
1140 } else {
1141 ALOGD("App switch was abandoned.");
1142 }
1143#endif
1144}
1145
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001147 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148}
1149
1150bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001151 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 return false;
1153 }
1154
1155 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001156 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001157 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001159 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160
1161 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001162 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 return true;
1164}
1165
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001166void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1167 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168}
1169
1170void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001171 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001172 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001173 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 releaseInboundEventLocked(entry);
1175 }
1176 traceInboundQueueLengthLocked();
1177}
1178
1179void InputDispatcher::releasePendingEventLocked() {
1180 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001182 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 }
1184}
1185
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001186void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001188 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189#if DEBUG_DISPATCH_CYCLE
1190 ALOGD("Injected inbound event was dropped.");
1191#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001192 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001195 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
1197 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198}
1199
1200void InputDispatcher::resetKeyRepeatLocked() {
1201 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001202 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204}
1205
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001206std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1207 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208
Michael Wright2e732952014-09-24 13:26:59 -07001209 uint32_t policyFlags = entry->policyFlags &
1210 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001212 std::shared_ptr<KeyEntry> newEntry =
1213 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1214 entry->source, entry->displayId, policyFlags, entry->action,
1215 entry->flags, entry->keyCode, entry->scanCode,
1216 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001218 newEntry->syntheticRepeat = true;
1219 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001221 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222}
1223
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001224bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001227 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228#endif
1229
1230 // Reset key repeating in case a keyboard device was added or removed or something.
1231 resetKeyRepeatLocked();
1232
1233 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001234 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1235 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001237 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 return true;
1239}
1240
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1242 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1245 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246#endif
1247
liushenxiang42232912021-05-21 20:24:09 +08001248 // Reset key repeating in case a keyboard device was disabled or enabled.
1249 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1250 resetKeyRepeatLocked();
1251 }
1252
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001253 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 synthesizeCancelationEventsForAllConnectionsLocked(options);
1256 return true;
1257}
1258
Vishnu Nairad321cd2020-08-20 16:40:21 -07001259void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001260 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001261 if (mPendingEvent != nullptr) {
1262 // Move the pending event to the front of the queue. This will give the chance
1263 // for the pending event to get dispatched to the newly focused window
1264 mInboundQueue.push_front(mPendingEvent);
1265 mPendingEvent = nullptr;
1266 }
1267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 std::unique_ptr<FocusEntry> focusEntry =
1269 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1270 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001271
1272 // This event should go to the front of the queue, but behind all other focus events
1273 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001275 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001276 [](const std::shared_ptr<EventEntry>& event) {
1277 return event->type == EventEntry::Type::FOCUS;
1278 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001279
1280 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001282}
1283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001285 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001286 if (channel == nullptr) {
1287 return; // Window has gone away
1288 }
1289 InputTarget target;
1290 target.inputChannel = channel;
1291 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1292 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001293 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1294 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001295 std::string reason = std::string("reason=").append(entry->reason);
1296 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001297 dispatchEventLocked(currentTime, entry, {target});
1298}
1299
Prabir Pradhan99987712020-11-10 18:43:05 -08001300void InputDispatcher::dispatchPointerCaptureChangedLocked(
1301 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1302 DropReason& dropReason) {
1303 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001304 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1305 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1306 }
1307 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001308 // Pointer capture was already forcefully disabled because of focus change.
1309 dropReason = DropReason::NOT_DROPPED;
1310 return;
1311 }
1312
1313 // Set drop reason for early returns
1314 dropReason = DropReason::NO_POINTER_CAPTURE;
1315
1316 sp<IBinder> token;
1317 if (entry->pointerCaptureEnabled) {
1318 // Enable Pointer Capture
1319 if (!mFocusedWindowRequestedPointerCapture) {
1320 // This can happen if a window requests capture and immediately releases capture.
1321 ALOGW("No window requested Pointer Capture.");
1322 return;
1323 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001324 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001325 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1326 mWindowTokenWithPointerCapture = token;
1327 } else {
1328 // Disable Pointer Capture
1329 token = mWindowTokenWithPointerCapture;
1330 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001331 if (mFocusedWindowRequestedPointerCapture) {
1332 mFocusedWindowRequestedPointerCapture = false;
1333 setPointerCaptureLocked(false);
1334 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001335 }
1336
1337 auto channel = getInputChannelLocked(token);
1338 if (channel == nullptr) {
1339 // Window has gone away, clean up Pointer Capture state.
1340 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001341 if (mFocusedWindowRequestedPointerCapture) {
1342 mFocusedWindowRequestedPointerCapture = false;
1343 setPointerCaptureLocked(false);
1344 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001345 return;
1346 }
1347 InputTarget target;
1348 target.inputChannel = channel;
1349 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1350 entry->dispatchInProgress = true;
1351 dispatchEventLocked(currentTime, entry, {target});
1352
1353 dropReason = DropReason::NOT_DROPPED;
1354}
1355
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001356bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001357 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001359 if (!entry->dispatchInProgress) {
1360 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1361 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1362 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1363 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001364 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 // We have seen two identical key downs in a row which indicates that the device
1366 // driver is automatically generating key repeats itself. We take note of the
1367 // repeat here, but we disable our own next key repeat timer since it is clear that
1368 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001369 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1370 // Make sure we don't get key down from a different device. If a different
1371 // device Id has same key pressed down, the new device Id will replace the
1372 // current one to hold the key repeat with repeat count reset.
1373 // In the future when got a KEY_UP on the device id, drop it and do not
1374 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1376 resetKeyRepeatLocked();
1377 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1378 } else {
1379 // Not a repeat. Save key down state in case we do see a repeat later.
1380 resetKeyRepeatLocked();
1381 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1382 }
1383 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001384 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1385 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001386 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001387#if DEBUG_INBOUND_EVENT_DETAILS
1388 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1389#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001390 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391 resetKeyRepeatLocked();
1392 }
1393
1394 if (entry->repeatCount == 1) {
1395 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1396 } else {
1397 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1398 }
1399
1400 entry->dispatchInProgress = true;
1401
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 }
1404
1405 // Handle case where the policy asked us to try again later last time.
1406 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1407 if (currentTime < entry->interceptKeyWakeupTime) {
1408 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1409 *nextWakeupTime = entry->interceptKeyWakeupTime;
1410 }
1411 return false; // wait until next wakeup
1412 }
1413 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1414 entry->interceptKeyWakeupTime = 0;
1415 }
1416
1417 // Give the policy a chance to intercept the key.
1418 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1419 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001420 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001421 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001422 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001423 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001424 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001426 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 return false; // wait for the command to run
1428 } else {
1429 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1430 }
1431 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001432 if (*dropReason == DropReason::NOT_DROPPED) {
1433 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435 }
1436
1437 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001438 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001439 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001440 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1441 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001442 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 return true;
1444 }
1445
1446 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001447 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001448 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001449 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001450 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return false;
1452 }
1453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001455 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 return true;
1457 }
1458
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001459 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001460 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461
1462 // Dispatch the key.
1463 dispatchEventLocked(currentTime, entry, inputTargets);
1464 return true;
1465}
1466
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001467void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001469 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001470 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1471 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001472 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1473 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1474 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475#endif
1476}
1477
Chris Yef59a2f42020-10-16 12:55:26 -07001478void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1479 mLock.unlock();
1480
1481 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1482 if (entry->accuracyChanged) {
1483 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1484 }
1485 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1486 entry->hwTimestamp, entry->values);
1487 mLock.lock();
1488}
1489
1490void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1491 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1492#if DEBUG_OUTBOUND_EVENT_DETAILS
1493 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1494 "source=0x%x, sensorType=%s",
1495 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001496 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001497#endif
1498 std::unique_ptr<CommandEntry> commandEntry =
1499 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1500 commandEntry->sensorEntry = entry;
1501 postCommandLocked(std::move(commandEntry));
1502}
1503
1504bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1505#if DEBUG_OUTBOUND_EVENT_DETAILS
1506 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1507 NamedEnum::string(sensorType).c_str());
1508#endif
1509 { // acquire lock
1510 std::scoped_lock _l(mLock);
1511
1512 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1513 std::shared_ptr<EventEntry> entry = *it;
1514 if (entry->type == EventEntry::Type::SENSOR) {
1515 it = mInboundQueue.erase(it);
1516 releaseInboundEventLocked(entry);
1517 }
1518 }
1519 }
1520 return true;
1521}
1522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001524 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001525 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001527 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 entry->dispatchInProgress = true;
1529
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001530 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532
1533 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001534 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001535 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001536 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1537 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 return true;
1539 }
1540
1541 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1542
1543 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001544 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545
1546 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 if (isPointerEvent) {
1549 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001551 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001552 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 } else {
1554 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001555 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001556 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001558 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 return false;
1560 }
1561
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001562 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001564 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1565 return true;
1566 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001567 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001568 CancelationOptions::Mode mode(isPointerEvent
1569 ? CancelationOptions::CANCEL_POINTER_EVENTS
1570 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1571 CancelationOptions options(mode, "input event injection failed");
1572 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 return true;
1574 }
1575
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001576 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001577 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578
1579 // Dispatch the motion.
1580 if (conflictingPointerActions) {
1581 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001582 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 synthesizeCancelationEventsForAllConnectionsLocked(options);
1584 }
1585 dispatchEventLocked(currentTime, entry, inputTargets);
1586 return true;
1587}
1588
chaviw98318de2021-05-19 16:45:23 -05001589void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001590 bool isExiting, const MotionEntry& motionEntry) {
1591 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1592 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1593 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1594 PointerCoords pointerCoords;
1595 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1596 pointerCoords.transform(windowHandle->getInfo()->transform);
1597
1598 std::unique_ptr<DragEntry> dragEntry =
1599 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1600 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1601 pointerCoords.getY());
1602
1603 enqueueInboundEventLocked(std::move(dragEntry));
1604}
1605
1606void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1607 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1608 if (channel == nullptr) {
1609 return; // Window has gone away
1610 }
1611 InputTarget target;
1612 target.inputChannel = channel;
1613 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1614 entry->dispatchInProgress = true;
1615 dispatchEventLocked(currentTime, entry, {target});
1616}
1617
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001618void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001620 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001621 ", policyFlags=0x%x, "
1622 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1623 "metaState=0x%x, buttonState=0x%x,"
1624 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001625 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1626 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1627 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001629 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001631 "x=%f, y=%f, pressure=%f, size=%f, "
1632 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1633 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001634 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1635 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1636 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1637 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1638 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1639 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1640 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1641 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1642 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1643 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 }
1645#endif
1646}
1647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001648void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1649 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001650 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001651 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652#if DEBUG_DISPATCH_CYCLE
1653 ALOGD("dispatchEventToCurrentInputTargets");
1654#endif
1655
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001656 updateInteractionTokensLocked(*eventEntry, inputTargets);
1657
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1659
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001660 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001662 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001663 sp<Connection> connection =
1664 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001665 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001666 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001668 if (DEBUG_FOCUS) {
1669 ALOGD("Dropping event delivery to target with channel '%s' because it "
1670 "is no longer registered with the input dispatcher.",
1671 inputTarget.inputChannel->getName().c_str());
1672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 }
1674 }
1675}
1676
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001677void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1678 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1679 // If the policy decides to close the app, we will get a channel removal event via
1680 // unregisterInputChannel, and will clean up the connection that way. We are already not
1681 // sending new pointers to the connection when it blocked, but focused events will continue to
1682 // pile up.
1683 ALOGW("Canceling events for %s because it is unresponsive",
1684 connection->inputChannel->getName().c_str());
1685 if (connection->status == Connection::STATUS_NORMAL) {
1686 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1687 "application not responding");
1688 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 }
1690}
1691
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001692void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001693 if (DEBUG_FOCUS) {
1694 ALOGD("Resetting ANR timeouts.");
1695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696
1697 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001698 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001699 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700}
1701
Tiger Huang721e26f2018-07-24 22:26:19 +08001702/**
1703 * Get the display id that the given event should go to. If this event specifies a valid display id,
1704 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1705 * Focused display is the display that the user most recently interacted with.
1706 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001707int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001708 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001709 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001710 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001711 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1712 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001713 break;
1714 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001715 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001716 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1717 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001718 break;
1719 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001720 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001721 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001722 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001723 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001724 case EventEntry::Type::SENSOR:
1725 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001726 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001727 return ADISPLAY_ID_NONE;
1728 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001729 }
1730 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1731}
1732
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001733bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1734 const char* focusedWindowName) {
1735 if (mAnrTracker.empty()) {
1736 // already processed all events that we waited for
1737 mKeyIsWaitingForEventsTimeout = std::nullopt;
1738 return false;
1739 }
1740
1741 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1742 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001743 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001744 mKeyIsWaitingForEventsTimeout = currentTime +
1745 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1746 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001747 return true;
1748 }
1749
1750 // We still have pending events, and already started the timer
1751 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1752 return true; // Still waiting
1753 }
1754
1755 // Waited too long, and some connection still hasn't processed all motions
1756 // Just send the key to the focused window
1757 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1758 focusedWindowName);
1759 mKeyIsWaitingForEventsTimeout = std::nullopt;
1760 return false;
1761}
1762
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001763InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1764 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1765 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001766 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767
Tiger Huang721e26f2018-07-24 22:26:19 +08001768 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001769 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001770 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001771 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1772
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 // If there is no currently focused window and no focused application
1774 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001775 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1776 ALOGI("Dropping %s event because there is no focused window or focused application in "
1777 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001778 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001779 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 }
1781
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001782 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1783 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1784 // start interacting with another application via touch (app switch). This code can be removed
1785 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1786 // an app is expected to have a focused window.
1787 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1788 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1789 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001790 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1791 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1792 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001793 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001794 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001795 ALOGW("Waiting because no window has focus but %s may eventually add a "
1796 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001797 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001798 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001799 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001800 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1801 // Already raised ANR. Drop the event
1802 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001803 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001805 } else {
1806 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001807 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001808 }
1809 }
1810
1811 // we have a valid, non-null focused window
1812 resetNoFocusedWindowTimeoutLocked();
1813
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001815 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001816 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 }
1818
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001819 if (focusedWindowHandle->getInfo()->paused) {
1820 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001821 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001822 }
1823
1824 // If the event is a key event, then we must wait for all previous events to
1825 // complete before delivering it because previous events may have the
1826 // side-effect of transferring focus to a different window and we want to
1827 // ensure that the following keys are sent to the new window.
1828 //
1829 // Suppose the user touches a button in a window then immediately presses "A".
1830 // If the button causes a pop-up window to appear then we want to ensure that
1831 // the "A" key is delivered to the new pop-up window. This is because users
1832 // often anticipate pending UI changes when typing on a keyboard.
1833 // To obtain this behavior, we must serialize key events with respect to all
1834 // prior input events.
1835 if (entry.type == EventEntry::Type::KEY) {
1836 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1837 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001838 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 }
1841
1842 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001843 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001844 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1845 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
1847 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849}
1850
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001851/**
1852 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1853 * that are currently unresponsive.
1854 */
1855std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1856 const std::vector<TouchedMonitor>& monitors) const {
1857 std::vector<TouchedMonitor> responsiveMonitors;
1858 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1859 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1860 sp<Connection> connection = getConnectionLocked(
1861 monitor.monitor.inputChannel->getConnectionToken());
1862 if (connection == nullptr) {
1863 ALOGE("Could not find connection for monitor %s",
1864 monitor.monitor.inputChannel->getName().c_str());
1865 return false;
1866 }
1867 if (!connection->responsive) {
1868 ALOGW("Unresponsive monitor %s will not get the new gesture",
1869 connection->inputChannel->getName().c_str());
1870 return false;
1871 }
1872 return true;
1873 });
1874 return responsiveMonitors;
1875}
1876
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1878 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1879 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001880 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 enum InjectionPermission {
1882 INJECTION_PERMISSION_UNKNOWN,
1883 INJECTION_PERMISSION_GRANTED,
1884 INJECTION_PERMISSION_DENIED
1885 };
1886
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 // For security reasons, we defer updating the touch state until we are sure that
1888 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001889 int32_t displayId = entry.displayId;
1890 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1892
1893 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001896 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1897 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001899 // Copy current touch state into tempTouchState.
1900 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1901 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001902 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001903 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001904 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1905 mTouchStatesByDisplay.find(displayId);
1906 if (oldStateIt != mTouchStatesByDisplay.end()) {
1907 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001908 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001909 }
1910
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001911 bool isSplit = tempTouchState.split;
1912 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1913 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1914 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001915 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1916 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1917 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1918 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1919 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001920 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 bool wrongDevice = false;
1922 if (newGesture) {
1923 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001924 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001925 ALOGI("Dropping event because a pointer for a different device is already down "
1926 "in display %" PRId32,
1927 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001928 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 switchedDevice = false;
1931 wrongDevice = true;
1932 goto Failed;
1933 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001934 tempTouchState.reset();
1935 tempTouchState.down = down;
1936 tempTouchState.deviceId = entry.deviceId;
1937 tempTouchState.source = entry.source;
1938 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001940 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001941 ALOGI("Dropping move event because a pointer for a different device is already active "
1942 "in display %" PRId32,
1943 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001944 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001945 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001946 switchedDevice = false;
1947 wrongDevice = true;
1948 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 }
1950
1951 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1952 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1953
Garfield Tan00f511d2019-06-12 16:55:40 -07001954 int32_t x;
1955 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001957 // Always dispatch mouse events to cursor position.
1958 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001959 x = int32_t(entry.xCursorPosition);
1960 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001961 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001962 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1963 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001964 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001965 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001966 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1967 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001968
1969 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001970 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00001971 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001974 if (newTouchedWindowHandle != nullptr &&
1975 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001976 // New window supports splitting, but we should never split mouse events.
1977 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 } else if (isSplit) {
1979 // New window does not support splitting but we have already split events.
1980 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001981 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
1983
1984 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001985 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001987 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001988 }
1989
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001990 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1991 ALOGI("Not sending touch event to %s because it is paused",
1992 newTouchedWindowHandle->getName().c_str());
1993 newTouchedWindowHandle = nullptr;
1994 }
1995
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001996 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001997 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001998 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1999 if (!isResponsive) {
2000 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002001 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2002 newTouchedWindowHandle = nullptr;
2003 }
2004 }
2005
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002006 // Drop events that can't be trusted due to occlusion
2007 if (newTouchedWindowHandle != nullptr &&
2008 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2009 TouchOcclusionInfo occlusionInfo =
2010 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002011 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002012 if (DEBUG_TOUCH_OCCLUSION) {
2013 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2014 for (const auto& log : occlusionInfo.debugInfo) {
2015 ALOGD("%s", log.c_str());
2016 }
2017 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002018 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2019 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2020 ALOGW("Dropping untrusted touch event due to %s/%d",
2021 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2022 newTouchedWindowHandle = nullptr;
2023 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002024 }
2025 }
2026
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 // Also don't send the new touch event to unresponsive gesture monitors
2028 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2029
Michael Wright3dd60e22019-03-27 22:06:44 +00002030 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2031 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002032 "(%d, %d) in display %" PRId32 ".",
2033 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002034 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002035 goto Failed;
2036 }
2037
2038 if (newTouchedWindowHandle != nullptr) {
2039 // Set target flags.
2040 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2041 if (isSplit) {
2042 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002044 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2045 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2046 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2047 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2048 }
2049
2050 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002051 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2052 newHoverWindowHandle = nullptr;
2053 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002054 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002055 }
2056
2057 // Update the temporary touch state.
2058 BitSet32 pointerIds;
2059 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002060 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002061 pointerIds.markBit(pointerId);
2062 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002063 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002066 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 } else {
2068 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2069
2070 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002071 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002072 if (DEBUG_FOCUS) {
2073 ALOGD("Dropping event because the pointer is not down or we previously "
2074 "dropped the pointer down event in display %" PRId32,
2075 displayId);
2076 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002077 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 goto Failed;
2079 }
2080
arthurhung6d4bed92021-03-17 11:59:33 +08002081 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002082
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002084 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002085 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002086 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2087 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088
chaviw98318de2021-05-19 16:45:23 -05002089 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002090 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002091 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2093 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002094 if (DEBUG_FOCUS) {
2095 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2096 oldTouchedWindowHandle->getName().c_str(),
2097 newTouchedWindowHandle->getName().c_str(), displayId);
2098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2101 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2102 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103
2104 // Make a slippery entrance into the new window.
2105 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2106 isSplit = true;
2107 }
2108
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002109 int32_t targetFlags =
2110 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 if (isSplit) {
2112 targetFlags |= InputTarget::FLAG_SPLIT;
2113 }
2114 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2115 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002116 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2117 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 }
2119
2120 BitSet32 pointerIds;
2121 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002122 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002124 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 }
2126 }
2127 }
2128
2129 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002130 // Let the previous window know that the hover sequence is over, unless we already did it
2131 // when dispatching it as is to newTouchedWindowHandle.
2132 if (mLastHoverWindowHandle != nullptr &&
2133 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2134 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135#if DEBUG_HOVER
2136 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002137 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002139 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2140 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 }
2142
Garfield Tandf26e862020-07-01 20:18:19 -07002143 // Let the new window know that the hover sequence is starting, unless we already did it
2144 // when dispatching it as is to newTouchedWindowHandle.
2145 if (newHoverWindowHandle != nullptr &&
2146 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2147 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148#if DEBUG_HOVER
2149 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002150 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002152 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2153 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2154 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156 }
2157
2158 // Check permission to inject into all touched foreground windows and ensure there
2159 // is at least one touched foreground window.
2160 {
2161 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002162 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2164 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002165 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002166 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 injectionPermission = INJECTION_PERMISSION_DENIED;
2168 goto Failed;
2169 }
2170 }
2171 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002172 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002173 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002174 ALOGI("Dropping event because there is no touched foreground window in display "
2175 "%" PRId32 " or gesture monitor to receive it.",
2176 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002177 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 goto Failed;
2179 }
2180
2181 // Permission granted to injection into all touched foreground windows.
2182 injectionPermission = INJECTION_PERMISSION_GRANTED;
2183 }
2184
2185 // Check whether windows listening for outside touches are owned by the same UID. If it is
2186 // set the policy flag that we will not reveal coordinate information to this window.
2187 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002188 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002190 if (foregroundWindowHandle) {
2191 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002192 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002193 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002194 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2195 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2196 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002197 InputTarget::FLAG_ZERO_COORDS,
2198 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201 }
2202 }
2203 }
2204
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 // If this is the first pointer going down and the touched window has a wallpaper
2206 // then also add the touched wallpaper windows so they are locked in for the duration
2207 // of the touch gesture.
2208 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2209 // engine only supports touch events. We would need to add a mechanism similar
2210 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2211 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002212 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002214 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002215 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002216 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002217 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2218 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002220 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002221 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002222 .addOrUpdateWindow(windowHandle,
2223 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2224 InputTarget::
2225 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2226 InputTarget::FLAG_DISPATCH_AS_IS,
2227 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
2229 }
2230 }
2231 }
2232
2233 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002234 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002236 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002238 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 }
2240
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002241 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002242 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002243 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002244 }
2245
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 // Drop the outside or hover touch windows since we will not care about them
2247 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002248 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249
2250Failed:
2251 // Check injection permission once and for all.
2252 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002253 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 injectionPermission = INJECTION_PERMISSION_GRANTED;
2255 } else {
2256 injectionPermission = INJECTION_PERMISSION_DENIED;
2257 }
2258 }
2259
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002260 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2261 return injectionResult;
2262 }
2263
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002265 if (!wrongDevice) {
2266 if (switchedDevice) {
2267 if (DEBUG_FOCUS) {
2268 ALOGD("Conflicting pointer actions: Switched to a different device.");
2269 }
2270 *outConflictingPointerActions = true;
2271 }
2272
2273 if (isHoverAction) {
2274 // Started hovering, therefore no longer down.
2275 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002276 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002277 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2278 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 *outConflictingPointerActions = true;
2281 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002282 tempTouchState.reset();
2283 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2284 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2285 tempTouchState.deviceId = entry.deviceId;
2286 tempTouchState.source = entry.source;
2287 tempTouchState.displayId = displayId;
2288 }
2289 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2290 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2291 // All pointers up or canceled.
2292 tempTouchState.reset();
2293 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2294 // First pointer went down.
2295 if (oldState && oldState->down) {
2296 if (DEBUG_FOCUS) {
2297 ALOGD("Conflicting pointer actions: Down received while already down.");
2298 }
2299 *outConflictingPointerActions = true;
2300 }
2301 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2302 // One pointer went up.
2303 if (isSplit) {
2304 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2305 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002307 for (size_t i = 0; i < tempTouchState.windows.size();) {
2308 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2309 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2310 touchedWindow.pointerIds.clearBit(pointerId);
2311 if (touchedWindow.pointerIds.isEmpty()) {
2312 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2313 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002316 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002318 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002319 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002320
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002321 // Save changes unless the action was scroll in which case the temporary touch
2322 // state was only valid for this one action.
2323 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2324 if (tempTouchState.displayId >= 0) {
2325 mTouchStatesByDisplay[displayId] = tempTouchState;
2326 } else {
2327 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002331 // Update hover state.
2332 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 }
2334
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 return injectionResult;
2336}
2337
arthurhung6d4bed92021-03-17 11:59:33 +08002338void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002339 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002340 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002341 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002342 if (dropWindow) {
2343 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2344 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002345 } else {
2346 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002347 }
2348 mDragState.reset();
2349}
2350
2351void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2352 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002353 return;
2354 }
2355
arthurhung6d4bed92021-03-17 11:59:33 +08002356 if (!mDragState->isStartDrag) {
2357 mDragState->isStartDrag = true;
2358 mDragState->isStylusButtonDownAtStart =
2359 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2360 }
2361
arthurhungb89ccb02020-12-30 16:19:01 +08002362 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2363 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2364 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2365 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002366 // Handle the special case : stylus button no longer pressed.
2367 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2368 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2369 finishDragAndDrop(entry.displayId, x, y);
2370 return;
2371 }
2372
chaviw98318de2021-05-19 16:45:23 -05002373 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002374 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002375 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002376 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002377 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2378 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2379 if (mDragState->dragHoverWindowHandle != nullptr) {
2380 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2381 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002382 }
arthurhung6d4bed92021-03-17 11:59:33 +08002383 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002384 }
2385 // enqueue drag location if needed.
2386 if (hoverWindowHandle != nullptr) {
2387 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2388 }
arthurhung6d4bed92021-03-17 11:59:33 +08002389 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2390 finishDragAndDrop(entry.displayId, x, y);
2391 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002392 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002393 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002394 }
2395}
2396
chaviw98318de2021-05-19 16:45:23 -05002397void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398 int32_t targetFlags, BitSet32 pointerIds,
2399 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002400 std::vector<InputTarget>::iterator it =
2401 std::find_if(inputTargets.begin(), inputTargets.end(),
2402 [&windowHandle](const InputTarget& inputTarget) {
2403 return inputTarget.inputChannel->getConnectionToken() ==
2404 windowHandle->getToken();
2405 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002406
chaviw98318de2021-05-19 16:45:23 -05002407 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002408
2409 if (it == inputTargets.end()) {
2410 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002411 std::shared_ptr<InputChannel> inputChannel =
2412 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002413 if (inputChannel == nullptr) {
2414 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2415 return;
2416 }
2417 inputTarget.inputChannel = inputChannel;
2418 inputTarget.flags = targetFlags;
2419 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002420 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002421 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002422 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002423 inputTargets.push_back(inputTarget);
2424 it = inputTargets.end() - 1;
2425 }
2426
2427 ALOG_ASSERT(it->flags == targetFlags);
2428 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2429
chaviw1ff3d1e2020-07-01 15:53:47 -07002430 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431}
2432
Michael Wright3dd60e22019-03-27 22:06:44 +00002433void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002434 int32_t displayId, float xOffset,
2435 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002436 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2437 mGlobalMonitorsByDisplay.find(displayId);
2438
2439 if (it != mGlobalMonitorsByDisplay.end()) {
2440 const std::vector<Monitor>& monitors = it->second;
2441 for (const Monitor& monitor : monitors) {
2442 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 }
2445}
2446
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002447void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2448 float yOffset,
2449 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002450 InputTarget target;
2451 target.inputChannel = monitor.inputChannel;
2452 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002453 ui::Transform t;
2454 t.set(xOffset, yOffset);
2455 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002456 inputTargets.push_back(target);
2457}
2458
chaviw98318de2021-05-19 16:45:23 -05002459bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002460 const InjectionState* injectionState) {
2461 if (injectionState &&
2462 (windowHandle == nullptr ||
2463 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2464 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002465 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 "owned by uid %d",
2468 injectionState->injectorPid, injectionState->injectorUid,
2469 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 } else {
2471 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002472 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 }
2474 return false;
2475 }
2476 return true;
2477}
2478
Robert Carrc9bf1d32020-04-13 17:21:08 -07002479/**
2480 * Indicate whether one window handle should be considered as obscuring
2481 * another window handle. We only check a few preconditions. Actually
2482 * checking the bounds is left to the caller.
2483 */
chaviw98318de2021-05-19 16:45:23 -05002484static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2485 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002486 // Compare by token so cloned layers aren't counted
2487 if (haveSameToken(windowHandle, otherHandle)) {
2488 return false;
2489 }
2490 auto info = windowHandle->getInfo();
2491 auto otherInfo = otherHandle->getInfo();
2492 if (!otherInfo->visible) {
2493 return false;
chaviw98318de2021-05-19 16:45:23 -05002494 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002495 // Those act as if they were invisible, so we don't need to flag them.
2496 // We do want to potentially flag touchable windows even if they have 0
2497 // opacity, since they can consume touches and alter the effects of the
2498 // user interaction (eg. apps that rely on
2499 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2500 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2501 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002502 } else if (info->ownerUid == otherInfo->ownerUid) {
2503 // If ownerUid is the same we don't generate occlusion events as there
2504 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002505 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002506 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002507 return false;
2508 } else if (otherInfo->displayId != info->displayId) {
2509 return false;
2510 }
2511 return true;
2512}
2513
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002514/**
2515 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2516 * untrusted, one should check:
2517 *
2518 * 1. If result.hasBlockingOcclusion is true.
2519 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2520 * BLOCK_UNTRUSTED.
2521 *
2522 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2523 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2524 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2525 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2526 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2527 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2528 *
2529 * If neither of those is true, then it means the touch can be allowed.
2530 */
2531InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002532 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2533 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002534 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002535 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002536 TouchOcclusionInfo info;
2537 info.hasBlockingOcclusion = false;
2538 info.obscuringOpacity = 0;
2539 info.obscuringUid = -1;
2540 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002541 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002542 if (windowHandle == otherHandle) {
2543 break; // All future windows are below us. Exit early.
2544 }
chaviw98318de2021-05-19 16:45:23 -05002545 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002546 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2547 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002548 if (DEBUG_TOUCH_OCCLUSION) {
2549 info.debugInfo.push_back(
2550 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2551 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002552 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2553 // we perform the checks below to see if the touch can be propagated or not based on the
2554 // window's touch occlusion mode
2555 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2556 info.hasBlockingOcclusion = true;
2557 info.obscuringUid = otherInfo->ownerUid;
2558 info.obscuringPackage = otherInfo->packageName;
2559 break;
2560 }
2561 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2562 uint32_t uid = otherInfo->ownerUid;
2563 float opacity =
2564 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2565 // Given windows A and B:
2566 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2567 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2568 opacityByUid[uid] = opacity;
2569 if (opacity > info.obscuringOpacity) {
2570 info.obscuringOpacity = opacity;
2571 info.obscuringUid = uid;
2572 info.obscuringPackage = otherInfo->packageName;
2573 }
2574 }
2575 }
2576 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002577 if (DEBUG_TOUCH_OCCLUSION) {
2578 info.debugInfo.push_back(
2579 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2580 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002581 return info;
2582}
2583
chaviw98318de2021-05-19 16:45:23 -05002584std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002585 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002586 return StringPrintf(INDENT2
2587 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2588 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2589 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2590 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002591 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002592 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002593 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002594 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2595 info->frameTop, info->frameRight, info->frameBottom,
2596 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002597 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2598 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2599 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002600}
2601
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002602bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2603 if (occlusionInfo.hasBlockingOcclusion) {
2604 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2605 occlusionInfo.obscuringUid);
2606 return false;
2607 }
2608 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2609 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2610 "%.2f, maximum allowed = %.2f)",
2611 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2612 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2613 return false;
2614 }
2615 return true;
2616}
2617
chaviw98318de2021-05-19 16:45:23 -05002618bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002619 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002621 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2622 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002623 if (windowHandle == otherHandle) {
2624 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 }
chaviw98318de2021-05-19 16:45:23 -05002626 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002627 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002628 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 return true;
2630 }
2631 }
2632 return false;
2633}
2634
chaviw98318de2021-05-19 16:45:23 -05002635bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002636 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002637 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2638 const WindowInfo* windowInfo = windowHandle->getInfo();
2639 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002640 if (windowHandle == otherHandle) {
2641 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002642 }
chaviw98318de2021-05-19 16:45:23 -05002643 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002644 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002645 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002646 return true;
2647 }
2648 }
2649 return false;
2650}
2651
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002652std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002653 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002654 if (applicationHandle != nullptr) {
2655 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002656 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 } else {
2658 return applicationHandle->getName();
2659 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002660 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002661 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002663 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 }
2665}
2666
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002667void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002668 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002669 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2670 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002671 // Focus or pointer capture changed events are passed to apps, but do not represent user
2672 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002673 return;
2674 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002675 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002676 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002677 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002678 const WindowInfo* info = focusedWindowHandle->getInfo();
2679 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002681 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682#endif
2683 return;
2684 }
2685 }
2686
2687 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002688 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002689 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002690 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2691 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 return;
2693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002695 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002696 eventType = USER_ACTIVITY_EVENT_TOUCH;
2697 }
2698 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002700 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002701 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2702 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002703 return;
2704 }
2705 eventType = USER_ACTIVITY_EVENT_BUTTON;
2706 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002708 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002709 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002710 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002711 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002712 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2713 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002714 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002715 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002716 break;
2717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 }
2719
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002720 std::unique_ptr<CommandEntry> commandEntry =
2721 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002722 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002724 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002725 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726}
2727
2728void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002730 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002731 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002732 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002734 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002735 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002736 ATRACE_NAME(message.c_str());
2737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738#if DEBUG_DISPATCH_CYCLE
2739 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002740 "globalScaleFactor=%f, pointerIds=0x%x %s",
2741 connection->getInputChannelName().c_str(), inputTarget.flags,
2742 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2743 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744#endif
2745
2746 // Skip this event if the connection status is not normal.
2747 // We don't want to enqueue additional outbound events if the connection is broken.
2748 if (connection->status != Connection::STATUS_NORMAL) {
2749#if DEBUG_DISPATCH_CYCLE
2750 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752#endif
2753 return;
2754 }
2755
2756 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002757 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2758 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2759 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002760 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002762 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002763 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002764 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002765 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 if (!splitMotionEntry) {
2767 return; // split event was dropped
2768 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002769 if (DEBUG_FOCUS) {
2770 ALOGD("channel '%s' ~ Split motion event.",
2771 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002772 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002773 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002774 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2775 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 return;
2777 }
2778 }
2779
2780 // Not splitting. Enqueue dispatch entries for the event as is.
2781 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2782}
2783
2784void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002786 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002787 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002788 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002789 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002790 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002791 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002792 ATRACE_NAME(message.c_str());
2793 }
2794
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002795 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796
2797 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002798 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002799 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002800 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002802 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002803 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002804 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002806 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002808 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002809 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810
2811 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002812 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 startDispatchCycleLocked(currentTime, connection);
2814 }
2815}
2816
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002818 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002819 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002820 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002821 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002822 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2823 connection->getInputChannelName().c_str(),
2824 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002825 ATRACE_NAME(message.c_str());
2826 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002827 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 if (!(inputTargetFlags & dispatchMode)) {
2829 return;
2830 }
2831 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2832
2833 // This is a new event.
2834 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002835 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002836 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002838 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2839 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002840 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002842 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002843 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002844 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002845 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002846 dispatchEntry->resolvedAction = keyEntry.action;
2847 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2850 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002852 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2853 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002855 return; // skip the inconsistent event
2856 }
2857 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002860 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002861 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002862 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2863 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2864 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2865 static_cast<int32_t>(IdGenerator::Source::OTHER);
2866 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002867 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2868 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2869 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2870 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2871 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2872 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2873 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2874 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2875 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2876 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2877 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002878 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002879 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002880 }
2881 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002882 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2883 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2886 "event",
2887 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002889 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2890 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2896 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2897 }
2898 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2899 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2903 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2906 "event",
2907 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 return; // skip the inconsistent event
2910 }
2911
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002912 dispatchEntry->resolvedEventId =
2913 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2914 ? mIdGenerator.nextId()
2915 : motionEntry.id;
2916 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2917 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2918 ") to MotionEvent(id=0x%" PRIx32 ").",
2919 motionEntry.id, dispatchEntry->resolvedEventId);
2920 ATRACE_NAME(message.c_str());
2921 }
2922
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002923 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2924 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2925 // Skip reporting pointer down outside focus to the policy.
2926 break;
2927 }
2928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002929 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002930 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931
2932 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002934 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002935 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2936 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002937 break;
2938 }
Chris Yef59a2f42020-10-16 12:55:26 -07002939 case EventEntry::Type::SENSOR: {
2940 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2941 break;
2942 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002943 case EventEntry::Type::CONFIGURATION_CHANGED:
2944 case EventEntry::Type::DEVICE_RESET: {
2945 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002946 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002947 break;
2948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 }
2950
2951 // Remember that we are waiting for this dispatch to complete.
2952 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002953 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 }
2955
2956 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002957 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002958 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002959}
2960
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002961/**
2962 * This function is purely for debugging. It helps us understand where the user interaction
2963 * was taking place. For example, if user is touching launcher, we will see a log that user
2964 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2965 * We will see both launcher and wallpaper in that list.
2966 * Once the interaction with a particular set of connections starts, no new logs will be printed
2967 * until the set of interacted connections changes.
2968 *
2969 * The following items are skipped, to reduce the logspam:
2970 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2971 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2972 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2973 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2974 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002975 */
2976void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2977 const std::vector<InputTarget>& targets) {
2978 // Skip ACTION_UP events, and all events other than keys and motions
2979 if (entry.type == EventEntry::Type::KEY) {
2980 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2981 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2982 return;
2983 }
2984 } else if (entry.type == EventEntry::Type::MOTION) {
2985 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2986 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2987 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2988 return;
2989 }
2990 } else {
2991 return; // Not a key or a motion
2992 }
2993
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07002994 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002995 std::vector<sp<Connection>> newConnections;
2996 for (const InputTarget& target : targets) {
2997 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2998 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2999 continue; // Skip windows that receive ACTION_OUTSIDE
3000 }
3001
3002 sp<IBinder> token = target.inputChannel->getConnectionToken();
3003 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003004 if (connection == nullptr) {
3005 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003006 }
3007 newConnectionTokens.insert(std::move(token));
3008 newConnections.emplace_back(connection);
3009 }
3010 if (newConnectionTokens == mInteractionConnectionTokens) {
3011 return; // no change
3012 }
3013 mInteractionConnectionTokens = newConnectionTokens;
3014
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003015 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003016 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003017 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003018 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003019 std::string message = "Interaction with: " + targetList;
3020 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003021 message += "<none>";
3022 }
3023 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3024}
3025
chaviwfd6d3512019-03-25 13:23:49 -07003026void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003027 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003028 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003029 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3030 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003031 return;
3032 }
3033
Vishnu Nairc519ff72021-01-21 08:23:08 -08003034 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003035 if (focusedToken == token) {
3036 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003037 return;
3038 }
3039
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003040 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3041 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003042 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003043 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044}
3045
3046void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003048 if (ATRACE_ENABLED()) {
3049 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003051 ATRACE_NAME(message.c_str());
3052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055#endif
3056
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003057 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3058 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003060 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003061 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003062 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063
3064 // Publish the event.
3065 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003066 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3067 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003068 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003069 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3070 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003073 status = connection->inputPublisher
3074 .publishKeyEvent(dispatchEntry->seq,
3075 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3076 keyEntry.source, keyEntry.displayId,
3077 std::move(hmac), dispatchEntry->resolvedAction,
3078 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3079 keyEntry.scanCode, keyEntry.metaState,
3080 keyEntry.repeatCount, keyEntry.downTime,
3081 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003082 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 }
3084
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003085 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003086 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003089 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090
chaviw82357092020-01-28 13:13:06 -08003091 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003092 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3094 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003095 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003096 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3097 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003098 // Don't apply window scale here since we don't want scale to affect raw
3099 // coordinates. The scale will be sent back to the client and applied
3100 // later when requesting relative coordinates.
3101 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3102 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 }
3104 usingCoords = scaledCoords;
3105 }
3106 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 // We don't want the dispatch target to know.
3108 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003109 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 scaledCoords[i].clear();
3111 }
3112 usingCoords = scaledCoords;
3113 }
3114 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003115
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003116 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117
3118 // Publish the motion event.
3119 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003120 .publishMotionEvent(dispatchEntry->seq,
3121 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003122 motionEntry.deviceId, motionEntry.source,
3123 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003124 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003127 motionEntry.edgeFlags, motionEntry.metaState,
3128 motionEntry.buttonState,
3129 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003130 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 motionEntry.xPrecision, motionEntry.yPrecision,
3132 motionEntry.xCursorPosition,
3133 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003134 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003135 dispatchEntry->displaySize.x,
3136 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003137 motionEntry.downTime, motionEntry.eventTime,
3138 motionEntry.pointerCount,
3139 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 break;
3141 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003142
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003143 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003144 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003145 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003146 focusEntry.id,
3147 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003148 mInTouchMode);
3149 break;
3150 }
3151
Prabir Pradhan99987712020-11-10 18:43:05 -08003152 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3153 const auto& captureEntry =
3154 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3155 status = connection->inputPublisher
3156 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3157 captureEntry.pointerCaptureEnabled);
3158 break;
3159 }
3160
arthurhungb89ccb02020-12-30 16:19:01 +08003161 case EventEntry::Type::DRAG: {
3162 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3163 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3164 dragEntry.id, dragEntry.x,
3165 dragEntry.y,
3166 dragEntry.isExiting);
3167 break;
3168 }
3169
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003170 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003171 case EventEntry::Type::DEVICE_RESET:
3172 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003173 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003174 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
3178
3179 // Check the result.
3180 if (status) {
3181 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003182 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 "This is unexpected because the wait queue is empty, so the pipe "
3185 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003186 "event to it, status=%s(%d)",
3187 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3188 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3190 } else {
3191 // Pipe is full and we are waiting for the app to finish process some events
3192 // before sending more events to it.
3193#if DEBUG_DISPATCH_CYCLE
3194 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 "waiting for the application to catch up",
3196 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199 } else {
3200 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003201 "status=%s(%d)",
3202 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3203 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3205 }
3206 return;
3207 }
3208
3209 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003210 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3211 connection->outboundQueue.end(),
3212 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003213 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003214 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003215 if (connection->responsive) {
3216 mAnrTracker.insert(dispatchEntry->timeoutTime,
3217 connection->inputChannel->getConnectionToken());
3218 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003219 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 }
3221}
3222
chaviw09c8d2d2020-08-24 15:48:26 -07003223std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3224 size_t size;
3225 switch (event.type) {
3226 case VerifiedInputEvent::Type::KEY: {
3227 size = sizeof(VerifiedKeyEvent);
3228 break;
3229 }
3230 case VerifiedInputEvent::Type::MOTION: {
3231 size = sizeof(VerifiedMotionEvent);
3232 break;
3233 }
3234 }
3235 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3236 return mHmacKeyManager.sign(start, size);
3237}
3238
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003239const std::array<uint8_t, 32> InputDispatcher::getSignature(
3240 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3241 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3242 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3243 // Only sign events up and down events as the purely move events
3244 // are tied to their up/down counterparts so signing would be redundant.
3245 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3246 verifiedEvent.actionMasked = actionMasked;
3247 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003248 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003249 }
3250 return INVALID_HMAC;
3251}
3252
3253const std::array<uint8_t, 32> InputDispatcher::getSignature(
3254 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3255 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3256 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3257 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003258 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003259}
3260
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003262 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003263 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264#if DEBUG_DISPATCH_CYCLE
3265 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003266 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267#endif
3268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003269 if (connection->status == Connection::STATUS_BROKEN ||
3270 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 return;
3272 }
3273
3274 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003275 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276}
3277
3278void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 const sp<Connection>& connection,
3280 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281#if DEBUG_DISPATCH_CYCLE
3282 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284#endif
3285
3286 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003287 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003288 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003289 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003290 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291
3292 // The connection appears to be unrecoverably broken.
3293 // Ignore already broken or zombie connections.
3294 if (connection->status == Connection::STATUS_NORMAL) {
3295 connection->status = Connection::STATUS_BROKEN;
3296
3297 if (notify) {
3298 // Notify other system components.
3299 onDispatchCycleBrokenLocked(currentTime, connection);
3300 }
3301 }
3302}
3303
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003304void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3305 while (!queue.empty()) {
3306 DispatchEntry* dispatchEntry = queue.front();
3307 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003308 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
3310}
3311
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003312void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003314 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 }
3316 delete dispatchEntry;
3317}
3318
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003319int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3320 std::scoped_lock _l(mLock);
3321 sp<Connection> connection = getConnectionLocked(connectionToken);
3322 if (connection == nullptr) {
3323 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3324 connectionToken.get(), events);
3325 return 0; // remove the callback
3326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003328 bool notify;
3329 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3330 if (!(events & ALOOPER_EVENT_INPUT)) {
3331 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3332 "events=0x%x",
3333 connection->getInputChannelName().c_str(), events);
3334 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
3336
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003337 nsecs_t currentTime = now();
3338 bool gotOne = false;
3339 status_t status = OK;
3340 for (;;) {
3341 Result<InputPublisher::ConsumerResponse> result =
3342 connection->inputPublisher.receiveConsumerResponse();
3343 if (!result.ok()) {
3344 status = result.error().code();
3345 break;
3346 }
3347
3348 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3349 const InputPublisher::Finished& finish =
3350 std::get<InputPublisher::Finished>(*result);
3351 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3352 finish.consumeTime);
3353 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003354 if (shouldReportMetricsForConnection(*connection)) {
3355 const InputPublisher::Timeline& timeline =
3356 std::get<InputPublisher::Timeline>(*result);
3357 mLatencyTracker
3358 .trackGraphicsLatency(timeline.inputEventId,
3359 connection->inputChannel->getConnectionToken(),
3360 std::move(timeline.graphicsTimeline));
3361 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003362 }
3363 gotOne = true;
3364 }
3365 if (gotOne) {
3366 runCommandsLockedInterruptible();
3367 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 return 1;
3369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 }
3371
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003372 notify = status != DEAD_OBJECT || !connection->monitor;
3373 if (notify) {
3374 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3375 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3376 status);
3377 }
3378 } else {
3379 // Monitor channels are never explicitly unregistered.
3380 // We do it automatically when the remote endpoint is closed so don't warn about them.
3381 const bool stillHaveWindowHandle =
3382 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3383 notify = !connection->monitor && stillHaveWindowHandle;
3384 if (notify) {
3385 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3386 connection->getInputChannelName().c_str(), events);
3387 }
3388 }
3389
3390 // Remove the channel.
3391 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3392 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393}
3394
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003395void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003397 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003398 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400}
3401
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003402void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003403 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003404 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3405 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3406}
3407
3408void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3409 const CancelationOptions& options,
3410 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3411 for (const auto& it : monitorsByDisplay) {
3412 const std::vector<Monitor>& monitors = it.second;
3413 for (const Monitor& monitor : monitors) {
3414 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003415 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003416 }
3417}
3418
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003420 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003421 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003422 if (connection == nullptr) {
3423 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003425
3426 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427}
3428
3429void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3430 const sp<Connection>& connection, const CancelationOptions& options) {
3431 if (connection->status == Connection::STATUS_BROKEN) {
3432 return;
3433 }
3434
3435 nsecs_t currentTime = now();
3436
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003437 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003438 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003440 if (cancelationEvents.empty()) {
3441 return;
3442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003444 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3445 "with reality: %s, mode=%d.",
3446 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3447 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003449
3450 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003451 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003452 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3453 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003454 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003455 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003456 target.globalScaleFactor = windowInfo->globalScaleFactor;
3457 }
3458 target.inputChannel = connection->inputChannel;
3459 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3460
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003461 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003462 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003463 switch (cancelationEventEntry->type) {
3464 case EventEntry::Type::KEY: {
3465 logOutboundKeyDetails("cancel - ",
3466 static_cast<const KeyEntry&>(*cancelationEventEntry));
3467 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003469 case EventEntry::Type::MOTION: {
3470 logOutboundMotionDetails("cancel - ",
3471 static_cast<const MotionEntry&>(*cancelationEventEntry));
3472 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003474 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003475 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3476 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003477 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003478 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003479 break;
3480 }
3481 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003482 case EventEntry::Type::DEVICE_RESET:
3483 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003484 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003485 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003486 break;
3487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 }
3489
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003490 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3491 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003493
3494 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495}
3496
Svet Ganov5d3bc372020-01-26 23:11:07 -08003497void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3498 const sp<Connection>& connection) {
3499 if (connection->status == Connection::STATUS_BROKEN) {
3500 return;
3501 }
3502
3503 nsecs_t currentTime = now();
3504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003505 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003506 connection->inputState.synthesizePointerDownEvents(currentTime);
3507
3508 if (downEvents.empty()) {
3509 return;
3510 }
3511
3512#if DEBUG_OUTBOUND_EVENT_DETAILS
3513 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3514 connection->getInputChannelName().c_str(), downEvents.size());
3515#endif
3516
3517 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003518 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003519 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3520 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003521 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003522 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003523 target.globalScaleFactor = windowInfo->globalScaleFactor;
3524 }
3525 target.inputChannel = connection->inputChannel;
3526 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3527
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003528 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003529 switch (downEventEntry->type) {
3530 case EventEntry::Type::MOTION: {
3531 logOutboundMotionDetails("down - ",
3532 static_cast<const MotionEntry&>(*downEventEntry));
3533 break;
3534 }
3535
3536 case EventEntry::Type::KEY:
3537 case EventEntry::Type::FOCUS:
3538 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003539 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003540 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003541 case EventEntry::Type::SENSOR:
3542 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003543 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003544 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003545 break;
3546 }
3547 }
3548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003549 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3550 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003551 }
3552
3553 startDispatchCycleLocked(currentTime, connection);
3554}
3555
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003556std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3557 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 ALOG_ASSERT(pointerIds.value != 0);
3559
3560 uint32_t splitPointerIndexMap[MAX_POINTERS];
3561 PointerProperties splitPointerProperties[MAX_POINTERS];
3562 PointerCoords splitPointerCoords[MAX_POINTERS];
3563
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003564 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 uint32_t splitPointerCount = 0;
3566
3567 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003568 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003570 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 uint32_t pointerId = uint32_t(pointerProperties.id);
3572 if (pointerIds.hasBit(pointerId)) {
3573 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3574 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3575 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003576 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 splitPointerCount += 1;
3578 }
3579 }
3580
3581 if (splitPointerCount != pointerIds.count()) {
3582 // This is bad. We are missing some of the pointers that we expected to deliver.
3583 // Most likely this indicates that we received an ACTION_MOVE events that has
3584 // different pointer ids than we expected based on the previous ACTION_DOWN
3585 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3586 // in this way.
3587 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 "we expected there to be %d pointers. This probably means we received "
3589 "a broken sequence of pointer ids from the input device.",
3590 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003591 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 }
3593
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003594 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003596 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3597 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3599 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003600 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 uint32_t pointerId = uint32_t(pointerProperties.id);
3602 if (pointerIds.hasBit(pointerId)) {
3603 if (pointerIds.count() == 1) {
3604 // The first/last pointer went down/up.
3605 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003606 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003607 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3608 ? AMOTION_EVENT_ACTION_CANCEL
3609 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 } else {
3611 // A secondary pointer went down/up.
3612 uint32_t splitPointerIndex = 0;
3613 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3614 splitPointerIndex += 1;
3615 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003616 action = maskedAction |
3617 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619 } else {
3620 // An unrelated pointer changed.
3621 action = AMOTION_EVENT_ACTION_MOVE;
3622 }
3623 }
3624
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003625 int32_t newId = mIdGenerator.nextId();
3626 if (ATRACE_ENABLED()) {
3627 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3628 ") to MotionEvent(id=0x%" PRIx32 ").",
3629 originalMotionEntry.id, newId);
3630 ATRACE_NAME(message.c_str());
3631 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 std::unique_ptr<MotionEntry> splitMotionEntry =
3633 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3634 originalMotionEntry.deviceId, originalMotionEntry.source,
3635 originalMotionEntry.displayId,
3636 originalMotionEntry.policyFlags, action,
3637 originalMotionEntry.actionButton,
3638 originalMotionEntry.flags, originalMotionEntry.metaState,
3639 originalMotionEntry.buttonState,
3640 originalMotionEntry.classification,
3641 originalMotionEntry.edgeFlags,
3642 originalMotionEntry.xPrecision,
3643 originalMotionEntry.yPrecision,
3644 originalMotionEntry.xCursorPosition,
3645 originalMotionEntry.yCursorPosition,
3646 originalMotionEntry.downTime, splitPointerCount,
3647 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003649 if (originalMotionEntry.injectionState) {
3650 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 splitMotionEntry->injectionState->refCount += 1;
3652 }
3653
3654 return splitMotionEntry;
3655}
3656
3657void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3658#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003659 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660#endif
3661
3662 bool needWake;
3663 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003664 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003666 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3667 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3668 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 } // release lock
3670
3671 if (needWake) {
3672 mLooper->wake();
3673 }
3674}
3675
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003676/**
3677 * If one of the meta shortcuts is detected, process them here:
3678 * Meta + Backspace -> generate BACK
3679 * Meta + Enter -> generate HOME
3680 * This will potentially overwrite keyCode and metaState.
3681 */
3682void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003683 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003684 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3685 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3686 if (keyCode == AKEYCODE_DEL) {
3687 newKeyCode = AKEYCODE_BACK;
3688 } else if (keyCode == AKEYCODE_ENTER) {
3689 newKeyCode = AKEYCODE_HOME;
3690 }
3691 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003692 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003693 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003694 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003695 keyCode = newKeyCode;
3696 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3697 }
3698 } else if (action == AKEY_EVENT_ACTION_UP) {
3699 // In order to maintain a consistent stream of up and down events, check to see if the key
3700 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3701 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003702 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003703 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003704 auto replacementIt = mReplacedKeys.find(replacement);
3705 if (replacementIt != mReplacedKeys.end()) {
3706 keyCode = replacementIt->second;
3707 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003708 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3709 }
3710 }
3711}
3712
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3714#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003715 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3716 "policyFlags=0x%x, action=0x%x, "
3717 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3718 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3719 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3720 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721#endif
3722 if (!validateKeyEvent(args->action)) {
3723 return;
3724 }
3725
3726 uint32_t policyFlags = args->policyFlags;
3727 int32_t flags = args->flags;
3728 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003729 // InputDispatcher tracks and generates key repeats on behalf of
3730 // whatever notifies it, so repeatCount should always be set to 0
3731 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3733 policyFlags |= POLICY_FLAG_VIRTUAL;
3734 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 if (policyFlags & POLICY_FLAG_FUNCTION) {
3737 metaState |= AMETA_FUNCTION_ON;
3738 }
3739
3740 policyFlags |= POLICY_FLAG_TRUSTED;
3741
Michael Wright78f24442014-08-06 15:55:28 -07003742 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003743 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003744
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003746 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003747 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3748 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749
Michael Wright2b3c3302018-03-02 17:19:13 +00003750 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003752 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3753 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 bool needWake;
3758 { // acquire lock
3759 mLock.lock();
3760
3761 if (shouldSendKeyToInputFilterLocked(args)) {
3762 mLock.unlock();
3763
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003764 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3766 return; // event was consumed by the filter
3767 }
3768
3769 mLock.lock();
3770 }
3771
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003772 std::unique_ptr<KeyEntry> newEntry =
3773 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3774 args->displayId, policyFlags, args->action, flags,
3775 keyCode, args->scanCode, metaState, repeatCount,
3776 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003778 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 mLock.unlock();
3780 } // release lock
3781
3782 if (needWake) {
3783 mLooper->wake();
3784 }
3785}
3786
3787bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3788 return mInputFilterEnabled;
3789}
3790
3791void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3792#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003793 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3794 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003795 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3796 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003797 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003798 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3799 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3800 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3801 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 for (uint32_t i = 0; i < args->pointerCount; i++) {
3803 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 "x=%f, y=%f, pressure=%f, size=%f, "
3805 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3806 "orientation=%f",
3807 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3808 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3809 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3810 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3811 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3812 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3813 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3814 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3815 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3816 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
3818#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3820 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 return;
3822 }
3823
3824 uint32_t policyFlags = args->policyFlags;
3825 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003826
3827 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003828 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003829 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3830 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003831 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833
3834 bool needWake;
3835 { // acquire lock
3836 mLock.lock();
3837
3838 if (shouldSendMotionToInputFilterLocked(args)) {
3839 mLock.unlock();
3840
3841 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003842 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003843 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3844 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003845 args->metaState, args->buttonState, args->classification, transform,
3846 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003847 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3848 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3849 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850
3851 policyFlags |= POLICY_FLAG_FILTERED;
3852 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3853 return; // event was consumed by the filter
3854 }
3855
3856 mLock.lock();
3857 }
3858
3859 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003860 std::unique_ptr<MotionEntry> newEntry =
3861 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3862 args->source, args->displayId, policyFlags,
3863 args->action, args->actionButton, args->flags,
3864 args->metaState, args->buttonState,
3865 args->classification, args->edgeFlags,
3866 args->xPrecision, args->yPrecision,
3867 args->xCursorPosition, args->yCursorPosition,
3868 args->downTime, args->pointerCount,
3869 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003871 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3872 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3873 !mInputFilterEnabled) {
3874 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3875 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3876 }
3877
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003878 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 mLock.unlock();
3880 } // release lock
3881
3882 if (needWake) {
3883 mLooper->wake();
3884 }
3885}
3886
Chris Yef59a2f42020-10-16 12:55:26 -07003887void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3888#if DEBUG_INBOUND_EVENT_DETAILS
3889 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3890 " sensorType=%s",
3891 args->id, args->eventTime, args->deviceId, args->source,
3892 NamedEnum::string(args->sensorType).c_str());
3893#endif
3894
3895 bool needWake;
3896 { // acquire lock
3897 mLock.lock();
3898
3899 // Just enqueue a new sensor event.
3900 std::unique_ptr<SensorEntry> newEntry =
3901 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3902 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3903 args->sensorType, args->accuracy,
3904 args->accuracyChanged, args->values);
3905
3906 needWake = enqueueInboundEventLocked(std::move(newEntry));
3907 mLock.unlock();
3908 } // release lock
3909
3910 if (needWake) {
3911 mLooper->wake();
3912 }
3913}
3914
Chris Yefb552902021-02-03 17:18:37 -08003915void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3916#if DEBUG_INBOUND_EVENT_DETAILS
3917 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3918 args->deviceId, args->isOn);
3919#endif
3920 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3921}
3922
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003924 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925}
3926
3927void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3928#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003929 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003930 "switchMask=0x%08x",
3931 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932#endif
3933
3934 uint32_t policyFlags = args->policyFlags;
3935 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003936 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937}
3938
3939void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3940#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3942 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943#endif
3944
3945 bool needWake;
3946 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003947 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003949 std::unique_ptr<DeviceResetEntry> newEntry =
3950 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3951 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 } // release lock
3953
3954 if (needWake) {
3955 mLooper->wake();
3956 }
3957}
3958
Prabir Pradhan7e186182020-11-10 13:56:45 -08003959void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3960#if DEBUG_INBOUND_EVENT_DETAILS
3961 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3962 args->enabled ? "true" : "false");
3963#endif
3964
Prabir Pradhan99987712020-11-10 18:43:05 -08003965 bool needWake;
3966 { // acquire lock
3967 std::scoped_lock _l(mLock);
3968 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3969 args->enabled);
3970 needWake = enqueueInboundEventLocked(std::move(entry));
3971 } // release lock
3972
3973 if (needWake) {
3974 mLooper->wake();
3975 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003976}
3977
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003978InputEventInjectionResult InputDispatcher::injectInputEvent(
3979 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3980 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981#if DEBUG_INBOUND_EVENT_DETAILS
3982 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003983 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3984 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003986 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
3988 policyFlags |= POLICY_FLAG_INJECTED;
3989 if (hasInjectionPermission(injectorPid, injectorUid)) {
3990 policyFlags |= POLICY_FLAG_TRUSTED;
3991 }
3992
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003993 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003994 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
3995 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
3996 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
3997 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
3998 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003999 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004000 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004001 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004002 }
4003
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004004 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004006 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004007 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4008 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004009 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004010 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004013 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004014 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4015 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4016 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004017 int32_t keyCode = incomingKey.getKeyCode();
4018 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004019 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004020 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004021 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004022 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004023 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4024 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4025 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004027 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4028 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004029 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004030
4031 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4032 android::base::Timer t;
4033 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4034 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4035 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4036 std::to_string(t.duration().count()).c_str());
4037 }
4038 }
4039
4040 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004041 std::unique_ptr<KeyEntry> injectedEntry =
4042 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004043 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004044 incomingKey.getDisplayId(), policyFlags, action,
4045 flags, keyCode, incomingKey.getScanCode(), metaState,
4046 incomingKey.getRepeatCount(),
4047 incomingKey.getDownTime());
4048 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 }
4051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004053 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4054 int32_t action = motionEvent.getAction();
4055 size_t pointerCount = motionEvent.getPointerCount();
4056 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4057 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004058 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004059 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004061 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062 }
4063
4064 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004065 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004066 android::base::Timer t;
4067 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4068 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4069 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4070 std::to_string(t.duration().count()).c_str());
4071 }
4072 }
4073
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004074 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4075 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4076 }
4077
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004078 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004079 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4080 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004082 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4083 resolvedDeviceId, motionEvent.getSource(),
4084 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004085 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004086 motionEvent.getButtonState(),
4087 motionEvent.getClassification(),
4088 motionEvent.getEdgeFlags(),
4089 motionEvent.getXPrecision(),
4090 motionEvent.getYPrecision(),
4091 motionEvent.getRawXCursorPosition(),
4092 motionEvent.getRawYCursorPosition(),
4093 motionEvent.getDownTime(), uint32_t(pointerCount),
4094 pointerProperties, samplePointerCoords,
4095 motionEvent.getXOffset(),
4096 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004097 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004098 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004099 sampleEventTimes += 1;
4100 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004101 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004102 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4103 resolvedDeviceId, motionEvent.getSource(),
4104 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004105 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004106 motionEvent.getMetaState(),
4107 motionEvent.getButtonState(),
4108 motionEvent.getClassification(),
4109 motionEvent.getEdgeFlags(),
4110 motionEvent.getXPrecision(),
4111 motionEvent.getYPrecision(),
4112 motionEvent.getRawXCursorPosition(),
4113 motionEvent.getRawYCursorPosition(),
4114 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004115 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004116 samplePointerCoords, motionEvent.getXOffset(),
4117 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004119 }
4120 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004124 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004125 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 }
4127
4128 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004129 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 injectionState->injectionIsAsync = true;
4131 }
4132
4133 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004134 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135
4136 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004137 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004138 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004139 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 }
4141
4142 mLock.unlock();
4143
4144 if (needWake) {
4145 mLooper->wake();
4146 }
4147
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004148 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004150 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004152 if (syncMode == InputEventInjectionSync::NONE) {
4153 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 } else {
4155 for (;;) {
4156 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004157 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 break;
4159 }
4160
4161 nsecs_t remainingTimeout = endTime - now();
4162 if (remainingTimeout <= 0) {
4163#if DEBUG_INJECTION
4164 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004167 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 break;
4169 }
4170
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004171 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
4173
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004174 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4175 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 while (injectionState->pendingForegroundDispatches != 0) {
4177#if DEBUG_INJECTION
4178 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004179 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180#endif
4181 nsecs_t remainingTimeout = endTime - now();
4182 if (remainingTimeout <= 0) {
4183#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4185 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 break;
4189 }
4190
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004191 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193 }
4194 }
4195
4196 injectionState->release();
4197 } // release lock
4198
4199#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004200 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202#endif
4203
4204 return injectionResult;
4205}
4206
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004207std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004208 std::array<uint8_t, 32> calculatedHmac;
4209 std::unique_ptr<VerifiedInputEvent> result;
4210 switch (event.getType()) {
4211 case AINPUT_EVENT_TYPE_KEY: {
4212 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4213 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4214 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004215 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004216 break;
4217 }
4218 case AINPUT_EVENT_TYPE_MOTION: {
4219 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4220 VerifiedMotionEvent verifiedMotionEvent =
4221 verifiedMotionEventFromMotionEvent(motionEvent);
4222 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004223 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004224 break;
4225 }
4226 default: {
4227 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4228 return nullptr;
4229 }
4230 }
4231 if (calculatedHmac == INVALID_HMAC) {
4232 return nullptr;
4233 }
4234 if (calculatedHmac != event.getHmac()) {
4235 return nullptr;
4236 }
4237 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004238}
4239
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 return injectorUid == 0 ||
4242 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243}
4244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004245void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004246 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004247 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 if (injectionState) {
4249#if DEBUG_INJECTION
4250 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 "injectorPid=%d, injectorUid=%d",
4252 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253#endif
4254
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004255 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 // Log the outcome since the injector did not wait for the injection result.
4257 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004258 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 ALOGV("Asynchronous input event injection succeeded.");
4260 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004261 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 ALOGW("Asynchronous input event injection failed.");
4263 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004264 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 ALOGW("Asynchronous input event injection permission denied.");
4266 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004267 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 ALOGW("Asynchronous input event injection timed out.");
4269 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 case InputEventInjectionResult::PENDING:
4271 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4272 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274 }
4275
4276 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004277 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279}
4280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004281void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4282 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 if (injectionState) {
4284 injectionState->pendingForegroundDispatches += 1;
4285 }
4286}
4287
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004288void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4289 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 if (injectionState) {
4291 injectionState->pendingForegroundDispatches -= 1;
4292
4293 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004294 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 }
4296 }
4297}
4298
chaviw98318de2021-05-19 16:45:23 -05004299const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004300 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004301 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004302 auto it = mWindowHandlesByDisplay.find(displayId);
4303 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004304}
4305
chaviw98318de2021-05-19 16:45:23 -05004306sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004307 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004308 if (windowHandleToken == nullptr) {
4309 return nullptr;
4310 }
4311
Arthur Hungb92218b2018-08-14 12:00:21 +08004312 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004313 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4314 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004315 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004316 return windowHandle;
4317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
4319 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004320 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321}
4322
chaviw98318de2021-05-19 16:45:23 -05004323sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4324 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004325 if (windowHandleToken == nullptr) {
4326 return nullptr;
4327 }
4328
chaviw98318de2021-05-19 16:45:23 -05004329 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004330 if (windowHandle->getToken() == windowHandleToken) {
4331 return windowHandle;
4332 }
4333 }
4334 return nullptr;
4335}
4336
chaviw98318de2021-05-19 16:45:23 -05004337sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4338 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004339 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004340 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4341 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004342 if (handle->getId() == windowHandle->getId() &&
4343 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004344 if (windowHandle->getInfo()->displayId != it.first) {
4345 ALOGE("Found window %s in display %" PRId32
4346 ", but it should belong to display %" PRId32,
4347 windowHandle->getName().c_str(), it.first,
4348 windowHandle->getInfo()->displayId);
4349 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004350 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
4353 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004354 return nullptr;
4355}
4356
chaviw98318de2021-05-19 16:45:23 -05004357sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004358 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4359 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360}
4361
chaviw98318de2021-05-19 16:45:23 -05004362bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004363 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4364 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004365 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004366 if (connection != nullptr && noInputChannel) {
4367 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4368 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4369 return false;
4370 }
4371
4372 if (connection == nullptr) {
4373 if (!noInputChannel) {
4374 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4375 }
4376 return false;
4377 }
4378 if (!connection->responsive) {
4379 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4380 return false;
4381 }
4382 return true;
4383}
4384
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004385std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4386 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004387 auto connectionIt = mConnectionsByToken.find(token);
4388 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004389 return nullptr;
4390 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004391 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004392}
4393
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004394void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004395 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4396 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004397 // Remove all handles on a display if there are no windows left.
4398 mWindowHandlesByDisplay.erase(displayId);
4399 return;
4400 }
4401
4402 // Since we compare the pointer of input window handles across window updates, we need
4403 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004404 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4405 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4406 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004407 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004408 }
4409
chaviw98318de2021-05-19 16:45:23 -05004410 std::vector<sp<WindowInfoHandle>> newHandles;
4411 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004412 if (!handle->updateInfo()) {
4413 // handle no longer valid
4414 continue;
4415 }
4416
chaviw98318de2021-05-19 16:45:23 -05004417 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004418 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004419 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004420 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4421 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4422 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004423 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004424 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004425 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004426 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004427 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004428 }
4429
4430 if (info->displayId != displayId) {
4431 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4432 handle->getName().c_str(), displayId, info->displayId);
4433 continue;
4434 }
4435
Robert Carredd13602020-04-13 17:24:34 -07004436 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4437 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004438 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004439 oldHandle->updateFrom(handle);
4440 newHandles.push_back(oldHandle);
4441 } else {
4442 newHandles.push_back(handle);
4443 }
4444 }
4445
4446 // Insert or replace
4447 mWindowHandlesByDisplay[displayId] = newHandles;
4448}
4449
Arthur Hung72d8dc32020-03-28 00:48:39 +00004450void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004451 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004452 { // acquire lock
4453 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004454 for (const auto& [displayId, handles] : handlesPerDisplay) {
4455 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004456 }
4457 }
4458 // Wake up poll loop since it may need to make new input dispatching choices.
4459 mLooper->wake();
4460}
4461
Arthur Hungb92218b2018-08-14 12:00:21 +08004462/**
4463 * Called from InputManagerService, update window handle list by displayId that can receive input.
4464 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4465 * If set an empty list, remove all handles from the specific display.
4466 * For focused handle, check if need to change and send a cancel event to previous one.
4467 * For removed handle, check if need to send a cancel event if already in touch.
4468 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004469void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004470 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004471 if (DEBUG_FOCUS) {
4472 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004473 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004474 windowList += iwh->getName() + " ";
4475 }
4476 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004479 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004480 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004481 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004482 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004483 if (noInputWindow && window->getToken() != nullptr) {
4484 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4485 window->getName().c_str());
4486 window->releaseChannel();
4487 }
4488 }
4489
Arthur Hung72d8dc32020-03-28 00:48:39 +00004490 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004491 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004493 // Save the old windows' orientation by ID before it gets updated.
4494 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004495 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004496 oldWindowOrientations.emplace(handle->getId(),
4497 handle->getInfo()->transform.getOrientation());
4498 }
4499
chaviw98318de2021-05-19 16:45:23 -05004500 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004501
chaviw98318de2021-05-19 16:45:23 -05004502 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004503 if (mLastHoverWindowHandle &&
4504 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4505 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004506 mLastHoverWindowHandle = nullptr;
4507 }
4508
Vishnu Nairc519ff72021-01-21 08:23:08 -08004509 std::optional<FocusResolver::FocusChanges> changes =
4510 mFocusResolver.setInputWindows(displayId, windowHandles);
4511 if (changes) {
4512 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004515 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4516 mTouchStatesByDisplay.find(displayId);
4517 if (stateIt != mTouchStatesByDisplay.end()) {
4518 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004519 for (size_t i = 0; i < state.windows.size();) {
4520 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004521 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004522 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004523 ALOGD("Touched window was removed: %s in display %" PRId32,
4524 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004525 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004526 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004527 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4528 if (touchedInputChannel != nullptr) {
4529 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4530 "touched window was removed");
4531 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004533 state.windows.erase(state.windows.begin() + i);
4534 } else {
4535 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 }
4537 }
arthurhungb89ccb02020-12-30 16:19:01 +08004538
arthurhung6d4bed92021-03-17 11:59:33 +08004539 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004540 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004541 if (mDragState &&
4542 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004543 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004544 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004545 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004546 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004547
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004548 if (isPerWindowInputRotationEnabled()) {
4549 // Determine if the orientation of any of the input windows have changed, and cancel all
4550 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004551 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4552 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004553 if (newWindowHandle != nullptr &&
4554 newWindowHandle->getInfo()->transform.getOrientation() !=
4555 oldWindowOrientations[oldWindowHandle->getId()]) {
4556 std::shared_ptr<InputChannel> inputChannel =
4557 getInputChannelLocked(newWindowHandle->getToken());
4558 if (inputChannel != nullptr) {
4559 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4560 "touched window's orientation changed");
4561 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4562 }
4563 }
4564 }
4565 }
4566
Arthur Hung72d8dc32020-03-28 00:48:39 +00004567 // Release information for windows that are no longer present.
4568 // This ensures that unused input channels are released promptly.
4569 // Otherwise, they might stick around until the window handle is destroyed
4570 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004571 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004572 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004573 if (DEBUG_FOCUS) {
4574 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004575 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004576 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004577 // To avoid making too many calls into the compat framework, only
4578 // check for window flags when windows are going away.
4579 // TODO(b/157929241) : delete this. This is only needed temporarily
4580 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004581 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004582 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4583 oldWindowHandle->getName().c_str());
4584 if (mCompatService != nullptr) {
4585 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4586 oldWindowHandle->getInfo()->ownerUid);
4587 }
4588 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004589 }
chaviw291d88a2019-02-14 10:33:58 -08004590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591}
4592
4593void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004594 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004595 if (DEBUG_FOCUS) {
4596 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4597 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4598 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004599 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004600 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004601 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 } // release lock
4603
4604 // Wake up poll loop since it may need to make new input dispatching choices.
4605 mLooper->wake();
4606}
4607
Vishnu Nair599f1412021-06-21 10:39:58 -07004608void InputDispatcher::setFocusedApplicationLocked(
4609 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4610 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4611 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4612
4613 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4614 return; // This application is already focused. No need to wake up or change anything.
4615 }
4616
4617 // Set the new application handle.
4618 if (inputApplicationHandle != nullptr) {
4619 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4620 } else {
4621 mFocusedApplicationHandlesByDisplay.erase(displayId);
4622 }
4623
4624 // No matter what the old focused application was, stop waiting on it because it is
4625 // no longer focused.
4626 resetNoFocusedWindowTimeoutLocked();
4627}
4628
Tiger Huang721e26f2018-07-24 22:26:19 +08004629/**
4630 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4631 * the display not specified.
4632 *
4633 * We track any unreleased events for each window. If a window loses the ability to receive the
4634 * released event, we will send a cancel event to it. So when the focused display is changed, we
4635 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4636 * display. The display-specified events won't be affected.
4637 */
4638void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004639 if (DEBUG_FOCUS) {
4640 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4641 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004642 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004643 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004644
4645 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004646 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004647 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004648 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004649 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004650 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004651 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 CancelationOptions
4653 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4654 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004655 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004656 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4657 }
4658 }
4659 mFocusedDisplayId = displayId;
4660
Chris Ye3c2d6f52020-08-09 10:39:48 -07004661 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004662 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004663 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004664
Vishnu Nairad321cd2020-08-20 16:40:21 -07004665 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004666 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004667 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004668 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004669 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004670 }
4671 }
4672 }
4673
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004674 if (DEBUG_FOCUS) {
4675 logDispatchStateLocked();
4676 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004677 } // release lock
4678
4679 // Wake up poll loop since it may need to make new input dispatching choices.
4680 mLooper->wake();
4681}
4682
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004684 if (DEBUG_FOCUS) {
4685 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687
4688 bool changed;
4689 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004690 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691
4692 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4693 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004694 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 }
4696
4697 if (mDispatchEnabled && !enabled) {
4698 resetAndDropEverythingLocked("dispatcher is being disabled");
4699 }
4700
4701 mDispatchEnabled = enabled;
4702 mDispatchFrozen = frozen;
4703 changed = true;
4704 } else {
4705 changed = false;
4706 }
4707
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004708 if (DEBUG_FOCUS) {
4709 logDispatchStateLocked();
4710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 } // release lock
4712
4713 if (changed) {
4714 // Wake up poll loop since it may need to make new input dispatching choices.
4715 mLooper->wake();
4716 }
4717}
4718
4719void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004720 if (DEBUG_FOCUS) {
4721 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
4724 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004725 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726
4727 if (mInputFilterEnabled == enabled) {
4728 return;
4729 }
4730
4731 mInputFilterEnabled = enabled;
4732 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4733 } // release lock
4734
4735 // Wake up poll loop since there might be work to do to drop everything.
4736 mLooper->wake();
4737}
4738
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004739void InputDispatcher::setInTouchMode(bool inTouchMode) {
4740 std::scoped_lock lock(mLock);
4741 mInTouchMode = inTouchMode;
4742}
4743
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004744void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4745 if (opacity < 0 || opacity > 1) {
4746 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4747 return;
4748 }
4749
4750 std::scoped_lock lock(mLock);
4751 mMaximumObscuringOpacityForTouch = opacity;
4752}
4753
4754void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4755 std::scoped_lock lock(mLock);
4756 mBlockUntrustedTouchesMode = mode;
4757}
4758
arthurhungb89ccb02020-12-30 16:19:01 +08004759bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4760 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004761 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004762 if (DEBUG_FOCUS) {
4763 ALOGD("Trivial transfer to same window.");
4764 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004765 return true;
4766 }
4767
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004769 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770
chaviw98318de2021-05-19 16:45:23 -05004771 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4772 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004773 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004774 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 return false;
4776 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004777 if (DEBUG_FOCUS) {
4778 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4779 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004782 if (DEBUG_FOCUS) {
4783 ALOGD("Cannot transfer focus because windows are on different displays.");
4784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 return false;
4786 }
4787
4788 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004789 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4790 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004791 for (size_t i = 0; i < state.windows.size(); i++) {
4792 const TouchedWindow& touchedWindow = state.windows[i];
4793 if (touchedWindow.windowHandle == fromWindowHandle) {
4794 int32_t oldTargetFlags = touchedWindow.targetFlags;
4795 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004797 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 int32_t newTargetFlags = oldTargetFlags &
4800 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4801 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004802 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
arthurhungb89ccb02020-12-30 16:19:01 +08004804 // Store the dragging window.
4805 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004806 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004807 }
4808
Jeff Brownf086ddb2014-02-11 14:28:48 -08004809 found = true;
4810 goto Found;
4811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 }
4813 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004816 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004817 if (DEBUG_FOCUS) {
4818 ALOGD("Focus transfer failed because from window did not have focus.");
4819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 return false;
4821 }
4822
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004823 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4824 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004825 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004826 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 CancelationOptions
4828 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4829 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004831 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 }
4833
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004834 if (DEBUG_FOCUS) {
4835 logDispatchStateLocked();
4836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 } // release lock
4838
4839 // Wake up poll loop since it may need to make new input dispatching choices.
4840 mLooper->wake();
4841 return true;
4842}
4843
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004844// Binder call
4845bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4846 sp<IBinder> fromToken;
4847 { // acquire lock
4848 std::scoped_lock _l(mLock);
4849
chaviw98318de2021-05-19 16:45:23 -05004850 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004851 if (toWindowHandle == nullptr) {
4852 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4853 return false;
4854 }
4855
4856 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4857
4858 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4859 if (touchStateIt == mTouchStatesByDisplay.end()) {
4860 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4861 displayId);
4862 return false;
4863 }
4864
4865 TouchState& state = touchStateIt->second;
4866 if (state.windows.size() != 1) {
4867 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4868 state.windows.size());
4869 return false;
4870 }
4871 const TouchedWindow& touchedWindow = state.windows[0];
4872 fromToken = touchedWindow.windowHandle->getToken();
4873 } // release lock
4874
4875 return transferTouchFocus(fromToken, destChannelToken);
4876}
4877
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004879 if (DEBUG_FOCUS) {
4880 ALOGD("Resetting and dropping all events (%s).", reason);
4881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882
4883 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4884 synthesizeCancelationEventsForAllConnectionsLocked(options);
4885
4886 resetKeyRepeatLocked();
4887 releasePendingEventLocked();
4888 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004891 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004892 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004894 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895}
4896
4897void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004898 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 dumpDispatchStateLocked(dump);
4900
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004901 std::istringstream stream(dump);
4902 std::string line;
4903
4904 while (std::getline(stream, line, '\n')) {
4905 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 }
4907}
4908
Prabir Pradhan99987712020-11-10 18:43:05 -08004909std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4910 std::string dump;
4911
4912 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4913 toString(mFocusedWindowRequestedPointerCapture));
4914
4915 std::string windowName = "None";
4916 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05004917 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004918 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4919 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4920 : "token has capture without window";
4921 }
4922 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4923
4924 return dump;
4925}
4926
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004927void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004928 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4929 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4930 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004931 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
Tiger Huang721e26f2018-07-24 22:26:19 +08004933 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4934 dump += StringPrintf(INDENT "FocusedApplications:\n");
4935 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4936 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004937 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004938 const std::chrono::duration timeout =
4939 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004940 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004941 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004942 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004945 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004947
Vishnu Nairc519ff72021-01-21 08:23:08 -08004948 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004949 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004951 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004952 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004953 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4954 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004955 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004956 state.displayId, toString(state.down), toString(state.split),
4957 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004958 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004959 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004960 for (size_t i = 0; i < state.windows.size(); i++) {
4961 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004962 dump += StringPrintf(INDENT4
4963 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4964 i, touchedWindow.windowHandle->getName().c_str(),
4965 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004966 }
4967 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004968 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 }
4971 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004972 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 }
4974
arthurhung6d4bed92021-03-17 11:59:33 +08004975 if (mDragState) {
4976 dump += StringPrintf(INDENT "DragState:\n");
4977 mDragState->dump(dump, INDENT2);
4978 }
4979
Arthur Hungb92218b2018-08-14 12:00:21 +08004980 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004981 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004982 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004983 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004984 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004985 dump += INDENT2 "Windows:\n";
4986 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05004987 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
4988 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004990 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004991 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004992 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004993 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004994 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004995 "applicationInfo.name=%s, "
4996 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004997 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004998 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004999 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005000 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005001 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005002 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005003 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005004 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005005 windowInfo->frameLeft, windowInfo->frameTop,
5006 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005007 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005008 windowInfo->applicationInfo.name.c_str(),
5009 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005010 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005011 dump += StringPrintf(", inputFeatures=%s",
5012 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005013 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005014 "ms, trustedOverlay=%s, hasToken=%s, "
5015 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005017 millis(windowInfo->dispatchingTimeout),
5018 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005019 toString(windowInfo->token != nullptr),
5020 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005021 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005022 }
5023 } else {
5024 dump += INDENT2 "Windows: <none>\n";
5025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026 }
5027 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005028 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 }
5030
Michael Wright3dd60e22019-03-27 22:06:44 +00005031 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005032 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005033 const std::vector<Monitor>& monitors = it.second;
5034 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5035 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 }
5037 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005038 const std::vector<Monitor>& monitors = it.second;
5039 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5040 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005043 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044 }
5045
5046 nsecs_t currentTime = now();
5047
5048 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005049 if (!mRecentQueue.empty()) {
5050 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005051 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005052 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005053 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005054 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 }
5056 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005057 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 }
5059
5060 // Dump event currently being dispatched.
5061 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005062 dump += INDENT "PendingEvent:\n";
5063 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005064 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005065 dump += StringPrintf(", age=%" PRId64 "ms\n",
5066 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005068 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 }
5070
5071 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005072 if (!mInboundQueue.empty()) {
5073 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005074 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005075 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005076 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005077 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078 }
5079 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005080 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 }
5082
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005083 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005084 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005085 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5086 const KeyReplacement& replacement = pair.first;
5087 int32_t newKeyCode = pair.second;
5088 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005089 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005090 }
5091 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005092 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005093 }
5094
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005095 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005096 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005097 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005098 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005100 connection->inputChannel->getFd().get(),
5101 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005102 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005103 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005105 if (!connection->outboundQueue.empty()) {
5106 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5107 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005108 dump += dumpQueue(connection->outboundQueue, currentTime);
5109
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005111 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005114 if (!connection->waitQueue.empty()) {
5115 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5116 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005117 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005119 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 }
5121 }
5122 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005123 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 }
5125
5126 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005127 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5128 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005130 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 }
5132
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005133 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005134 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5135 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5136 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005137 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005138 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139}
5140
Michael Wright3dd60e22019-03-27 22:06:44 +00005141void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5142 const size_t numMonitors = monitors.size();
5143 for (size_t i = 0; i < numMonitors; i++) {
5144 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005145 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005146 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5147 dump += "\n";
5148 }
5149}
5150
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005151class LooperEventCallback : public LooperCallback {
5152public:
5153 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5154 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5155
5156private:
5157 std::function<int(int events)> mCallback;
5158};
5159
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005160Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005161#if DEBUG_CHANNEL_CREATION
5162 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163#endif
5164
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005165 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005166 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005167 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005168
5169 if (result) {
5170 return base::Error(result) << "Failed to open input channel pair with name " << name;
5171 }
5172
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005174 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005175 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005176 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005177 sp<Connection> connection =
5178 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005180 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5181 ALOGE("Created a new connection, but the token %p is already known", token.get());
5182 }
5183 mConnectionsByToken.emplace(token, connection);
5184
5185 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5186 this, std::placeholders::_1, token);
5187
5188 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 } // release lock
5190
5191 // Wake the looper because some connections have changed.
5192 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005193 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194}
5195
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005196Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5197 bool isGestureMonitor,
5198 const std::string& name,
5199 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005200 std::shared_ptr<InputChannel> serverChannel;
5201 std::unique_ptr<InputChannel> clientChannel;
5202 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5203 if (result) {
5204 return base::Error(result) << "Failed to open input channel pair with name " << name;
5205 }
5206
Michael Wright3dd60e22019-03-27 22:06:44 +00005207 { // acquire lock
5208 std::scoped_lock _l(mLock);
5209
5210 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005211 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5212 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005213 }
5214
Garfield Tan15601662020-09-22 15:32:38 -07005215 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005216 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005217 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005218
5219 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5220 ALOGE("Created a new connection, but the token %p is already known", token.get());
5221 }
5222 mConnectionsByToken.emplace(token, connection);
5223 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5224 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005226 auto& monitorsByDisplay =
5227 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005228 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005229
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005230 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005231 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5232 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005233 }
Garfield Tan15601662020-09-22 15:32:38 -07005234
Michael Wright3dd60e22019-03-27 22:06:44 +00005235 // Wake the looper because some connections have changed.
5236 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005237 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005238}
5239
Garfield Tan15601662020-09-22 15:32:38 -07005240status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005242 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243
Garfield Tan15601662020-09-22 15:32:38 -07005244 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 if (status) {
5246 return status;
5247 }
5248 } // release lock
5249
5250 // Wake the poll loop because removing the connection may have changed the current
5251 // synchronization state.
5252 mLooper->wake();
5253 return OK;
5254}
5255
Garfield Tan15601662020-09-22 15:32:38 -07005256status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5257 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005258 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005259 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005260 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 return BAD_VALUE;
5262 }
5263
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005264 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005265
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005267 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 }
5269
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005270 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271
5272 nsecs_t currentTime = now();
5273 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5274
5275 connection->status = Connection::STATUS_ZOMBIE;
5276 return OK;
5277}
5278
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005279void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5280 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5281 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005282}
5283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005284void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005285 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005286 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005287 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005288 std::vector<Monitor>& monitors = it->second;
5289 const size_t numMonitors = monitors.size();
5290 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005291 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005292 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5293 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005294 monitors.erase(monitors.begin() + i);
5295 break;
5296 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005297 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005298 if (monitors.empty()) {
5299 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005300 } else {
5301 ++it;
5302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 }
5304}
5305
Michael Wright3dd60e22019-03-27 22:06:44 +00005306status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5307 { // acquire lock
5308 std::scoped_lock _l(mLock);
5309 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5310
5311 if (!foundDisplayId) {
5312 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5313 return BAD_VALUE;
5314 }
5315 int32_t displayId = foundDisplayId.value();
5316
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005317 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5318 mTouchStatesByDisplay.find(displayId);
5319 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005320 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5321 return BAD_VALUE;
5322 }
5323
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005324 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005325 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005326 std::optional<int32_t> foundDeviceId;
5327 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005328 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005329 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005330 foundDeviceId = state.deviceId;
5331 }
5332 }
5333 if (!foundDeviceId || !state.down) {
5334 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005335 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005336 return BAD_VALUE;
5337 }
5338 int32_t deviceId = foundDeviceId.value();
5339
5340 // Send cancel events to all the input channels we're stealing from.
5341 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005342 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005343 options.deviceId = deviceId;
5344 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005345 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005346 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005347 std::shared_ptr<InputChannel> channel =
5348 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005349 if (channel != nullptr) {
5350 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005351 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005352 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005353 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005354 canceledWindows += "]";
5355 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5356 canceledWindows.c_str());
5357
Michael Wright3dd60e22019-03-27 22:06:44 +00005358 // Then clear the current touch state so we stop dispatching to them as well.
5359 state.filterNonMonitors();
5360 }
5361 return OK;
5362}
5363
Prabir Pradhan99987712020-11-10 18:43:05 -08005364void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5365 { // acquire lock
5366 std::scoped_lock _l(mLock);
5367 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005368 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005369 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5370 windowHandle != nullptr ? windowHandle->getName().c_str()
5371 : "token without window");
5372 }
5373
Vishnu Nairc519ff72021-01-21 08:23:08 -08005374 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005375 if (focusedToken != windowToken) {
5376 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5377 enabled ? "enable" : "disable");
5378 return;
5379 }
5380
5381 if (enabled == mFocusedWindowRequestedPointerCapture) {
5382 ALOGW("Ignoring request to %s Pointer Capture: "
5383 "window has %s requested pointer capture.",
5384 enabled ? "enable" : "disable", enabled ? "already" : "not");
5385 return;
5386 }
5387
5388 mFocusedWindowRequestedPointerCapture = enabled;
5389 setPointerCaptureLocked(enabled);
5390 } // release lock
5391
5392 // Wake the thread to process command entries.
5393 mLooper->wake();
5394}
5395
Michael Wright3dd60e22019-03-27 22:06:44 +00005396std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5397 const sp<IBinder>& token) {
5398 for (const auto& it : mGestureMonitorsByDisplay) {
5399 const std::vector<Monitor>& monitors = it.second;
5400 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005401 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005402 return it.first;
5403 }
5404 }
5405 }
5406 return std::nullopt;
5407}
5408
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005409std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5410 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5411 if (gesturePid.has_value()) {
5412 return gesturePid;
5413 }
5414 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5415}
5416
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005417sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005418 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005419 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005420 }
5421
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005422 for (const auto& [token, connection] : mConnectionsByToken) {
5423 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005424 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 }
5426 }
Robert Carr4e670e52018-08-15 13:26:12 -07005427
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005428 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429}
5430
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005431std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5432 sp<Connection> connection = getConnectionLocked(connectionToken);
5433 if (connection == nullptr) {
5434 return "<nullptr>";
5435 }
5436 return connection->getInputChannelName();
5437}
5438
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005439void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005440 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005441 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005442}
5443
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005444void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5445 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005446 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005447 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5448 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 commandEntry->connection = connection;
5450 commandEntry->eventTime = currentTime;
5451 commandEntry->seq = seq;
5452 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005453 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005454 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455}
5456
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005457void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5458 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005460 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005462 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5463 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005465 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466}
5467
Vishnu Nairad321cd2020-08-20 16:40:21 -07005468void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5469 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005470 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5471 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005472 commandEntry->oldToken = oldToken;
5473 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005474 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005475}
5476
arthurhungf452d0b2021-01-06 00:19:52 +08005477void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5478 std::unique_ptr<CommandEntry> commandEntry =
5479 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5480 commandEntry->newToken = token;
5481 commandEntry->x = x;
5482 commandEntry->y = y;
5483 postCommandLocked(std::move(commandEntry));
5484}
5485
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005486void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5487 if (connection == nullptr) {
5488 LOG_ALWAYS_FATAL("Caller must check for nullness");
5489 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005490 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5491 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005492 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005493 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005494 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005495 return;
5496 }
5497 /**
5498 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5499 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5500 * has changed. This could cause newer entries to time out before the already dispatched
5501 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5502 * processes the events linearly. So providing information about the oldest entry seems to be
5503 * most useful.
5504 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005505 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005506 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5507 std::string reason =
5508 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005509 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005510 ns2ms(currentWait),
5511 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005512 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005513 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005514
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005515 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5516
5517 // Stop waking up for events on this connection, it is already unresponsive
5518 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005519}
5520
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005521void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5522 std::string reason =
5523 StringPrintf("%s does not have a focused window", application->getName().c_str());
5524 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005525
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005526 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5527 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5528 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005529 postCommandLocked(std::move(commandEntry));
5530}
5531
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005532void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5533 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5534 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5535 commandEntry->obscuringPackage = obscuringPackage;
5536 postCommandLocked(std::move(commandEntry));
5537}
5538
chaviw98318de2021-05-19 16:45:23 -05005539void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005540 const std::string& reason) {
5541 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5542 updateLastAnrStateLocked(windowLabel, reason);
5543}
5544
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005545void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5546 const std::string& reason) {
5547 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005548 updateLastAnrStateLocked(windowLabel, reason);
5549}
5550
5551void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5552 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005554 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 struct tm tm;
5556 localtime_r(&t, &tm);
5557 char timestr[64];
5558 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005559 mLastAnrState.clear();
5560 mLastAnrState += INDENT "ANR:\n";
5561 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5563 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005564 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565}
5566
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005567void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 mLock.unlock();
5569
5570 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5571
5572 mLock.lock();
5573}
5574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005575void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 sp<Connection> connection = commandEntry->connection;
5577
5578 if (connection->status != Connection::STATUS_ZOMBIE) {
5579 mLock.unlock();
5580
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005581 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582
5583 mLock.lock();
5584 }
5585}
5586
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005587void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005588 sp<IBinder> oldToken = commandEntry->oldToken;
5589 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005590 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005591 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005592 mLock.lock();
5593}
5594
arthurhungf452d0b2021-01-06 00:19:52 +08005595void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5596 sp<IBinder> newToken = commandEntry->newToken;
5597 mLock.unlock();
5598 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5599 mLock.lock();
5600}
5601
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005602void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005604
5605 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5606
5607 mLock.lock();
5608}
5609
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005610void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005611 mLock.unlock();
5612
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005613 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614
5615 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005616}
5617
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005618void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005619 mLock.unlock();
5620
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005621 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5622
5623 mLock.lock();
5624}
5625
5626void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5627 mLock.unlock();
5628
5629 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5630
5631 mLock.lock();
5632}
5633
5634void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5635 mLock.unlock();
5636
5637 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005638
5639 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005640}
5641
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005642void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5643 mLock.unlock();
5644
5645 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5646
5647 mLock.lock();
5648}
5649
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5651 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005652 KeyEntry& entry = *(commandEntry->keyEntry);
5653 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654
5655 mLock.unlock();
5656
Michael Wright2b3c3302018-03-02 17:19:13 +00005657 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005658 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005659 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005660 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5661 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005662 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664
5665 mLock.lock();
5666
5667 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005668 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005670 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005671 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005672 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5673 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675}
5676
chaviwfd6d3512019-03-25 13:23:49 -07005677void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5678 mLock.unlock();
5679 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5680 mLock.lock();
5681}
5682
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005683/**
5684 * Connection is responsive if it has no events in the waitQueue that are older than the
5685 * current time.
5686 */
5687static bool isConnectionResponsive(const Connection& connection) {
5688 const nsecs_t currentTime = now();
5689 for (const DispatchEntry* entry : connection.waitQueue) {
5690 if (entry->timeoutTime < currentTime) {
5691 return false;
5692 }
5693 }
5694 return true;
5695}
5696
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005697void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005699 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005701 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702
5703 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005704 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005705 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005706 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005708 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005709 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005710 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005711 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5712 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005713 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005714 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5715 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5716 connection->inputChannel->getConnectionToken(),
5717 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5718 finishTime);
5719 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005720
5721 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005722 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005723 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005724 restartEvent =
5725 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005726 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005727 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005728 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5729 handled);
5730 } else {
5731 restartEvent = false;
5732 }
5733
5734 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005735 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005736 // contents of the wait queue to have been drained, so we need to double-check
5737 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005738 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5739 if (dispatchEntryIt != connection->waitQueue.end()) {
5740 dispatchEntry = *dispatchEntryIt;
5741 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005742 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5743 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005744 if (!connection->responsive) {
5745 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005746 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005747 // The connection was unresponsive, and now it's responsive.
5748 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005749 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005750 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005751 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005752 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005753 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005754 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005755 } else {
5756 releaseDispatchEntry(dispatchEntry);
5757 }
5758 }
5759
5760 // Start the next dispatch cycle for this connection.
5761 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762}
5763
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005764void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5765 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5766 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5767 monitorUnresponsiveCommand->pid = pid;
5768 monitorUnresponsiveCommand->reason = std::move(reason);
5769 postCommandLocked(std::move(monitorUnresponsiveCommand));
5770}
5771
5772void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5773 std::string reason) {
5774 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5775 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5776 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5777 windowUnresponsiveCommand->reason = std::move(reason);
5778 postCommandLocked(std::move(windowUnresponsiveCommand));
5779}
5780
5781void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5782 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5783 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5784 monitorResponsiveCommand->pid = pid;
5785 postCommandLocked(std::move(monitorResponsiveCommand));
5786}
5787
5788void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5789 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5790 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5791 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5792 postCommandLocked(std::move(windowResponsiveCommand));
5793}
5794
5795/**
5796 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5797 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5798 * command entry to the command queue.
5799 */
5800void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5801 std::string reason) {
5802 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5803 if (connection.monitor) {
5804 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5805 reason.c_str());
5806 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5807 if (!pid.has_value()) {
5808 ALOGE("Could not find unresponsive monitor for connection %s",
5809 connection.inputChannel->getName().c_str());
5810 return;
5811 }
5812 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5813 return;
5814 }
5815 // If not a monitor, must be a window
5816 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5817 reason.c_str());
5818 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5819}
5820
5821/**
5822 * Tell the policy that a connection has become responsive so that it can stop ANR.
5823 */
5824void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5825 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5826 if (connection.monitor) {
5827 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5828 if (!pid.has_value()) {
5829 ALOGE("Could not find responsive monitor for connection %s",
5830 connection.inputChannel->getName().c_str());
5831 return;
5832 }
5833 sendMonitorResponsiveCommandLocked(pid.value());
5834 return;
5835 }
5836 // If not a monitor, must be a window
5837 sendWindowResponsiveCommandLocked(connectionToken);
5838}
5839
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005841 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005842 KeyEntry& keyEntry, bool handled) {
5843 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005844 if (!handled) {
5845 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005846 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005847 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005848 return false;
5849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005851 // Get the fallback key state.
5852 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005853 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005854 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005855 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005856 connection->inputState.removeFallbackKey(originalKeyCode);
5857 }
5858
5859 if (handled || !dispatchEntry->hasForegroundTarget()) {
5860 // If the application handles the original key for which we previously
5861 // generated a fallback or if the window is not a foreground window,
5862 // then cancel the associated fallback key, if any.
5863 if (fallbackKeyCode != -1) {
5864 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005866 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005867 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005868 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005870 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005871 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872
5873 mLock.unlock();
5874
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005875 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005876 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877
5878 mLock.lock();
5879
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880 // Cancel the fallback key.
5881 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005883 "application handled the original non-fallback key "
5884 "or is no longer a foreground target, "
5885 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 options.keyCode = fallbackKeyCode;
5887 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889 connection->inputState.removeFallbackKey(originalKeyCode);
5890 }
5891 } else {
5892 // If the application did not handle a non-fallback key, first check
5893 // that we are in a good state to perform unhandled key event processing
5894 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005895 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005896 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005898 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005899 "since this is not an initial down. "
5900 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005901 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005903 return false;
5904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005906 // Dispatch the unhandled key to the policy.
5907#if DEBUG_OUTBOUND_EVENT_DETAILS
5908 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005909 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005910 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005911#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005912 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005913
5914 mLock.unlock();
5915
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005916 bool fallback =
5917 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005919
5920 mLock.lock();
5921
5922 if (connection->status != Connection::STATUS_NORMAL) {
5923 connection->inputState.removeFallbackKey(originalKeyCode);
5924 return false;
5925 }
5926
5927 // Latch the fallback keycode for this key on an initial down.
5928 // The fallback keycode cannot change at any other point in the lifecycle.
5929 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005931 fallbackKeyCode = event.getKeyCode();
5932 } else {
5933 fallbackKeyCode = AKEYCODE_UNKNOWN;
5934 }
5935 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5936 }
5937
5938 ALOG_ASSERT(fallbackKeyCode != -1);
5939
5940 // Cancel the fallback key if the policy decides not to send it anymore.
5941 // We will continue to dispatch the key to the policy but we will no
5942 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005943 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5944 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005945#if DEBUG_OUTBOUND_EVENT_DETAILS
5946 if (fallback) {
5947 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005948 "as a fallback for %d, but on the DOWN it had requested "
5949 "to send %d instead. Fallback canceled.",
5950 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005951 } else {
5952 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005953 "but on the DOWN it had requested to send %d. "
5954 "Fallback canceled.",
5955 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956 }
5957#endif
5958
5959 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5960 "canceling fallback, policy no longer desires it");
5961 options.keyCode = fallbackKeyCode;
5962 synthesizeCancelationEventsForConnectionLocked(connection, options);
5963
5964 fallback = false;
5965 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005966 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005967 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005968 }
5969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970
5971#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005972 {
5973 std::string msg;
5974 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5975 connection->inputState.getFallbackKeys();
5976 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005977 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005979 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005980 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005981 }
5982#endif
5983
5984 if (fallback) {
5985 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005986 keyEntry.eventTime = event.getEventTime();
5987 keyEntry.deviceId = event.getDeviceId();
5988 keyEntry.source = event.getSource();
5989 keyEntry.displayId = event.getDisplayId();
5990 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5991 keyEntry.keyCode = fallbackKeyCode;
5992 keyEntry.scanCode = event.getScanCode();
5993 keyEntry.metaState = event.getMetaState();
5994 keyEntry.repeatCount = event.getRepeatCount();
5995 keyEntry.downTime = event.getDownTime();
5996 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005997
5998#if DEBUG_OUTBOUND_EVENT_DETAILS
5999 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006000 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006001 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006002#endif
6003 return true; // restart the event
6004 } else {
6005#if DEBUG_OUTBOUND_EVENT_DETAILS
6006 ALOGD("Unhandled key event: No fallback key.");
6007#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006008
6009 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006010 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011 }
6012 }
6013 return false;
6014}
6015
6016bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006017 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006018 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006019 return false;
6020}
6021
6022void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6023 mLock.unlock();
6024
Sean Stoutb4e0a592021-02-23 07:34:53 -08006025 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6026 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027
6028 mLock.lock();
6029}
6030
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031void InputDispatcher::traceInboundQueueLengthLocked() {
6032 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006033 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034 }
6035}
6036
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006037void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 if (ATRACE_ENABLED()) {
6039 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006040 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6041 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042 }
6043}
6044
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006045void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 if (ATRACE_ENABLED()) {
6047 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006048 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6049 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 }
6051}
6052
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006053void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006054 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006056 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057 dumpDispatchStateLocked(dump);
6058
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006059 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006060 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006061 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006062 }
6063}
6064
6065void InputDispatcher::monitor() {
6066 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006067 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006069 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070}
6071
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006072/**
6073 * Wake up the dispatcher and wait until it processes all events and commands.
6074 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6075 * this method can be safely called from any thread, as long as you've ensured that
6076 * the work you are interested in completing has already been queued.
6077 */
6078bool InputDispatcher::waitForIdle() {
6079 /**
6080 * Timeout should represent the longest possible time that a device might spend processing
6081 * events and commands.
6082 */
6083 constexpr std::chrono::duration TIMEOUT = 100ms;
6084 std::unique_lock lock(mLock);
6085 mLooper->wake();
6086 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6087 return result == std::cv_status::no_timeout;
6088}
6089
Vishnu Naire798b472020-07-23 13:52:21 -07006090/**
6091 * Sets focus to the window identified by the token. This must be called
6092 * after updating any input window handles.
6093 *
6094 * Params:
6095 * request.token - input channel token used to identify the window that should gain focus.
6096 * request.focusedToken - the token that the caller expects currently to be focused. If the
6097 * specified token does not match the currently focused window, this request will be dropped.
6098 * If the specified focused token matches the currently focused window, the call will succeed.
6099 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6100 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6101 * when requesting the focus change. This determines which request gets
6102 * precedence if there is a focus change request from another source such as pointer down.
6103 */
Vishnu Nair958da932020-08-21 17:12:37 -07006104void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6105 { // acquire lock
6106 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006107 std::optional<FocusResolver::FocusChanges> changes =
6108 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6109 if (changes) {
6110 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006111 }
6112 } // release lock
6113 // Wake up poll loop since it may need to make new input dispatching choices.
6114 mLooper->wake();
6115}
6116
Vishnu Nairc519ff72021-01-21 08:23:08 -08006117void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6118 if (changes.oldFocus) {
6119 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006120 if (focusedInputChannel) {
6121 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6122 "focus left window");
6123 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006124 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006125 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006126 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006127 if (changes.newFocus) {
6128 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006129 }
6130
Prabir Pradhan99987712020-11-10 18:43:05 -08006131 // If a window has pointer capture, then it must have focus. We need to ensure that this
6132 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6133 // If the window loses focus before it loses pointer capture, then the window can be in a state
6134 // where it has pointer capture but not focus, violating the contract. Therefore we must
6135 // dispatch the pointer capture event before the focus event. Since focus events are added to
6136 // the front of the queue (above), we add the pointer capture event to the front of the queue
6137 // after the focus events are added. This ensures the pointer capture event ends up at the
6138 // front.
6139 disablePointerCaptureForcedLocked();
6140
Vishnu Nairc519ff72021-01-21 08:23:08 -08006141 if (mFocusedDisplayId == changes.displayId) {
6142 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006143 }
6144}
Vishnu Nair958da932020-08-21 17:12:37 -07006145
Prabir Pradhan99987712020-11-10 18:43:05 -08006146void InputDispatcher::disablePointerCaptureForcedLocked() {
6147 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6148 return;
6149 }
6150
6151 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6152
6153 if (mFocusedWindowRequestedPointerCapture) {
6154 mFocusedWindowRequestedPointerCapture = false;
6155 setPointerCaptureLocked(false);
6156 }
6157
6158 if (!mWindowTokenWithPointerCapture) {
6159 // No need to send capture changes because no window has capture.
6160 return;
6161 }
6162
6163 if (mPendingEvent != nullptr) {
6164 // Move the pending event to the front of the queue. This will give the chance
6165 // for the pending event to be dropped if it is a captured event.
6166 mInboundQueue.push_front(mPendingEvent);
6167 mPendingEvent = nullptr;
6168 }
6169
6170 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6171 false /* hasCapture */);
6172 mInboundQueue.push_front(std::move(entry));
6173}
6174
Prabir Pradhan99987712020-11-10 18:43:05 -08006175void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6176 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6177 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6178 commandEntry->enabled = enabled;
6179 postCommandLocked(std::move(commandEntry));
6180}
6181
6182void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6183 android::inputdispatcher::CommandEntry* commandEntry) {
6184 mLock.unlock();
6185
6186 mPolicy->setPointerCapture(commandEntry->enabled);
6187
6188 mLock.lock();
6189}
6190
Vishnu Nair599f1412021-06-21 10:39:58 -07006191void InputDispatcher::displayRemoved(int32_t displayId) {
6192 { // acquire lock
6193 std::scoped_lock _l(mLock);
6194 // Set an empty list to remove all handles from the specific display.
6195 setInputWindowsLocked(/* window handles */ {}, displayId);
6196 setFocusedApplicationLocked(displayId, nullptr);
6197 // Call focus resolver to clean up stale requests. This must be called after input windows
6198 // have been removed for the removed display.
6199 mFocusResolver.displayRemoved(displayId);
6200 } // release lock
6201
6202 // Wake up poll loop since it may need to make new input dispatching choices.
6203 mLooper->wake();
6204}
6205
Garfield Tane84e6f92019-08-29 17:28:41 -07006206} // namespace android::inputdispatcher