blob: cecfb3308aa666b50471d586f801f14e27ff7ad5 [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*/,
334 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900335 }
336 }
337
chaviw1ff3d1e2020-07-01 15:53:47 -0700338 if (inputTarget.useDefaultPointerTransform()) {
339 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700340 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700341 inputTarget.globalScaleFactor,
342 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000343 }
344
345 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
346 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700348 std::vector<PointerCoords> pointerCoords;
349 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000350
351 // Use the first pointer information to normalize all other pointers. This could be any pointer
352 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 // uses the transform for the normalized pointer.
354 const ui::Transform& firstPointerTransform =
355 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
356 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357
358 // Iterate through all pointers in the event to normalize against the first.
359 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
360 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
361 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700362 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000363
364 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700365 // First, apply the current pointer's transform to update the coordinates into
366 // window space.
367 pointerCoords[pointerIndex].transform(currTransform);
368 // Next, apply the inverse transform of the normalized coordinates so the
369 // current coordinates are transformed into the normalized coordinate space.
370 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371 }
372
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700373 std::unique_ptr<MotionEntry> combinedMotionEntry =
374 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
375 motionEntry.deviceId, motionEntry.source,
376 motionEntry.displayId, motionEntry.policyFlags,
377 motionEntry.action, motionEntry.actionButton,
378 motionEntry.flags, motionEntry.metaState,
379 motionEntry.buttonState, motionEntry.classification,
380 motionEntry.edgeFlags, motionEntry.xPrecision,
381 motionEntry.yPrecision, motionEntry.xCursorPosition,
382 motionEntry.yCursorPosition, motionEntry.downTime,
383 motionEntry.pointerCount, motionEntry.pointerProperties,
384 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000385
386 if (motionEntry.injectionState) {
387 combinedMotionEntry->injectionState = motionEntry.injectionState;
388 combinedMotionEntry->injectionState->refCount += 1;
389 }
390
391 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700392 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700393 firstPointerTransform, inputTarget.globalScaleFactor,
394 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000395 return dispatchEntry;
396}
397
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700398static void addGestureMonitors(const std::vector<Monitor>& monitors,
399 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
400 float yOffset = 0) {
401 if (monitors.empty()) {
402 return;
403 }
404 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
405 for (const Monitor& monitor : monitors) {
406 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
407 }
408}
409
Garfield Tan15601662020-09-22 15:32:38 -0700410static status_t openInputChannelPair(const std::string& name,
411 std::shared_ptr<InputChannel>& serverChannel,
412 std::unique_ptr<InputChannel>& clientChannel) {
413 std::unique_ptr<InputChannel> uniqueServerChannel;
414 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
415
416 serverChannel = std::move(uniqueServerChannel);
417 return result;
418}
419
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500420template <typename T>
421static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
422 if (lhs == nullptr && rhs == nullptr) {
423 return true;
424 }
425 if (lhs == nullptr || rhs == nullptr) {
426 return false;
427 }
428 return *lhs == *rhs;
429}
430
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000431static sp<IPlatformCompatNative> getCompatService() {
432 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
433 if (service == nullptr) {
434 ALOGE("Failed to link to compat service");
435 return nullptr;
436 }
437 return interface_cast<IPlatformCompatNative>(service);
438}
439
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000440static KeyEvent createKeyEvent(const KeyEntry& entry) {
441 KeyEvent event;
442 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
443 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
444 entry.repeatCount, entry.downTime, entry.eventTime);
445 return event;
446}
447
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000448static std::optional<int32_t> findMonitorPidByToken(
449 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
450 const sp<IBinder>& token) {
451 for (const auto& it : monitorsByDisplay) {
452 const std::vector<Monitor>& monitors = it.second;
453 for (const Monitor& monitor : monitors) {
454 if (monitor.inputChannel->getConnectionToken() == token) {
455 return monitor.pid;
456 }
457 }
458 }
459 return std::nullopt;
460}
461
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000462static bool shouldReportMetricsForConnection(const Connection& connection) {
463 // Do not keep track of gesture monitors. They receive every event and would disproportionately
464 // affect the statistics.
465 if (connection.monitor) {
466 return false;
467 }
468 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
469 if (!connection.responsive) {
470 return false;
471 }
472 return true;
473}
474
475static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
476 const Connection& connection) {
477 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
478 const int32_t& inputEventId = eventEntry.id;
479 if (inputEventId != dispatchEntry.resolvedEventId) {
480 // Event was transmuted
481 return false;
482 }
483 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
484 return false;
485 }
486 // Only track latency for events that originated from hardware
487 if (eventEntry.isSynthesized()) {
488 return false;
489 }
490 const EventEntry::Type& inputEventEntryType = eventEntry.type;
491 if (inputEventEntryType == EventEntry::Type::KEY) {
492 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
493 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
494 return false;
495 }
496 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
497 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
498 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
499 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
500 return false;
501 }
502 } else {
503 // Not a key or a motion
504 return false;
505 }
506 if (!shouldReportMetricsForConnection(connection)) {
507 return false;
508 }
509 return true;
510}
511
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512// --- InputDispatcher ---
513
Garfield Tan00f511d2019-06-12 16:55:40 -0700514InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
515 : mPolicy(policy),
516 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700517 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800518 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700519 mAppSwitchSawKeyDown(false),
520 mAppSwitchDueTime(LONG_LONG_MAX),
521 mNextUnblockedEvent(nullptr),
522 mDispatchEnabled(false),
523 mDispatchFrozen(false),
524 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800525 // mInTouchMode will be initialized by the WindowManager to the default device config.
526 // To avoid leaking stack in case that call never comes, and for tests,
527 // initialize it here anyways.
528 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100529 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000530 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800531 mFocusedWindowRequestedPointerCapture(false),
532 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000533 mLatencyAggregator(),
534 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000535 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800537 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800538
Yi Kong9b14ac62018-07-17 13:48:38 -0700539 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540
541 policy->getDispatcherConfiguration(&mConfig);
542}
543
544InputDispatcher::~InputDispatcher() {
545 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800546 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547
548 resetKeyRepeatLocked();
549 releasePendingEventLocked();
550 drainInboundQueueLocked();
551 }
552
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000553 while (!mConnectionsByToken.empty()) {
554 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700555 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 }
557}
558
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700559status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700560 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700561 return ALREADY_EXISTS;
562 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700563 mThread = std::make_unique<InputThread>(
564 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
565 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700566}
567
568status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700569 if (mThread && mThread->isCallingThread()) {
570 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700571 return INVALID_OPERATION;
572 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700573 mThread.reset();
574 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700575}
576
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577void InputDispatcher::dispatchOnce() {
578 nsecs_t nextWakeupTime = LONG_LONG_MAX;
579 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800580 std::scoped_lock _l(mLock);
581 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582
583 // Run a dispatch loop if there are no pending commands.
584 // The dispatch loop might enqueue commands to run afterwards.
585 if (!haveCommandsLocked()) {
586 dispatchOnceInnerLocked(&nextWakeupTime);
587 }
588
589 // Run all pending commands if there are any.
590 // If any commands were run then force the next poll to wake up immediately.
591 if (runCommandsLockedInterruptible()) {
592 nextWakeupTime = LONG_LONG_MIN;
593 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800594
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700595 // If we are still waiting for ack on some events,
596 // we might have to wake up earlier to check if an app is anr'ing.
597 const nsecs_t nextAnrCheck = processAnrsLocked();
598 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
599
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800600 // We are about to enter an infinitely long sleep, because we have no commands or
601 // pending or queued events
602 if (nextWakeupTime == LONG_LONG_MAX) {
603 mDispatcherEnteredIdle.notify_all();
604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 } // release lock
606
607 // Wait for callback or timeout or wake. (make sure we round up, not down)
608 nsecs_t currentTime = now();
609 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
610 mLooper->pollOnce(timeoutMillis);
611}
612
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700613/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500614 * Raise ANR if there is no focused window.
615 * Before the ANR is raised, do a final state check:
616 * 1. The currently focused application must be the same one we are waiting for.
617 * 2. Ensure we still don't have a focused window.
618 */
619void InputDispatcher::processNoFocusedWindowAnrLocked() {
620 // Check if the application that we are waiting for is still focused.
621 std::shared_ptr<InputApplicationHandle> focusedApplication =
622 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
623 if (focusedApplication == nullptr ||
624 focusedApplication->getApplicationToken() !=
625 mAwaitedFocusedApplication->getApplicationToken()) {
626 // Unexpected because we should have reset the ANR timer when focused application changed
627 ALOGE("Waited for a focused window, but focused application has already changed to %s",
628 focusedApplication->getName().c_str());
629 return; // The focused application has changed.
630 }
631
chaviw98318de2021-05-19 16:45:23 -0500632 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500633 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
634 if (focusedWindowHandle != nullptr) {
635 return; // We now have a focused window. No need for ANR.
636 }
637 onAnrLocked(mAwaitedFocusedApplication);
638}
639
640/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700641 * Check if any of the connections' wait queues have events that are too old.
642 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
643 * Return the time at which we should wake up next.
644 */
645nsecs_t InputDispatcher::processAnrsLocked() {
646 const nsecs_t currentTime = now();
647 nsecs_t nextAnrCheck = LONG_LONG_MAX;
648 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
649 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
650 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500651 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700652 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500653 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700654 return LONG_LONG_MIN;
655 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500656 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700657 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
658 }
659 }
660
661 // Check if any connection ANRs are due
662 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
663 if (currentTime < nextAnrCheck) { // most likely scenario
664 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
665 }
666
667 // If we reached here, we have an unresponsive connection.
668 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
669 if (connection == nullptr) {
670 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
671 return nextAnrCheck;
672 }
673 connection->responsive = false;
674 // Stop waking up for this unresponsive connection
675 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000676 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700677 return LONG_LONG_MIN;
678}
679
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500680std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500681 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700682 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500683 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700684 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500685 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700686}
687
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
689 nsecs_t currentTime = now();
690
Jeff Browndc5992e2014-04-11 01:27:26 -0700691 // Reset the key repeat timer whenever normal dispatch is suspended while the
692 // device is in a non-interactive state. This is to ensure that we abort a key
693 // repeat if the device is just coming out of sleep.
694 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 resetKeyRepeatLocked();
696 }
697
698 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
699 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100700 if (DEBUG_FOCUS) {
701 ALOGD("Dispatch frozen. Waiting some more.");
702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 return;
704 }
705
706 // Optimize latency of app switches.
707 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
708 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
709 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
710 if (mAppSwitchDueTime < *nextWakeupTime) {
711 *nextWakeupTime = mAppSwitchDueTime;
712 }
713
714 // Ready to start a new event.
715 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700717 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 if (isAppSwitchDue) {
719 // The inbound queue is empty so the app switch key we were waiting
720 // for will never arrive. Stop waiting for it.
721 resetPendingAppSwitchLocked(false);
722 isAppSwitchDue = false;
723 }
724
725 // Synthesize a key repeat if appropriate.
726 if (mKeyRepeatState.lastKeyEntry) {
727 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
728 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
729 } else {
730 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
731 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
732 }
733 }
734 }
735
736 // Nothing to do if there is no pending event.
737 if (!mPendingEvent) {
738 return;
739 }
740 } else {
741 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700742 mPendingEvent = mInboundQueue.front();
743 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 traceInboundQueueLengthLocked();
745 }
746
747 // Poke user activity for this event.
748 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700749 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 }
752
753 // Now we have an event to dispatch.
754 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700755 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700757 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700759 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700761 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 }
763
764 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700765 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 }
767
768 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700769 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700770 const ConfigurationChangedEntry& typedEntry =
771 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700772 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 break;
775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700777 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700778 const DeviceResetEntry& typedEntry =
779 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 break;
783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100785 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700786 std::shared_ptr<FocusEntry> typedEntry =
787 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100788 dispatchFocusLocked(currentTime, typedEntry);
789 done = true;
790 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
791 break;
792 }
793
Prabir Pradhan99987712020-11-10 18:43:05 -0800794 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
795 const auto typedEntry =
796 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
797 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
798 done = true;
799 break;
800 }
801
arthurhungb89ccb02020-12-30 16:19:01 +0800802 case EventEntry::Type::DRAG: {
803 std::shared_ptr<DragEntry> typedEntry =
804 std::static_pointer_cast<DragEntry>(mPendingEvent);
805 dispatchDragLocked(currentTime, typedEntry);
806 done = true;
807 break;
808 }
809
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700810 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700811 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700813 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 resetPendingAppSwitchLocked(true);
815 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 } else if (dropReason == DropReason::NOT_DROPPED) {
817 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 }
819 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700821 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700823 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
824 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700826 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 break;
828 }
829
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700830 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700831 std::shared_ptr<MotionEntry> motionEntry =
832 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700833 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
834 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700836 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700837 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700839 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
840 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700841 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700842 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 }
Chris Yef59a2f42020-10-16 12:55:26 -0700845
846 case EventEntry::Type::SENSOR: {
847 std::shared_ptr<SensorEntry> sensorEntry =
848 std::static_pointer_cast<SensorEntry>(mPendingEvent);
849 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
850 dropReason = DropReason::APP_SWITCH;
851 }
852 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
853 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
854 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
855 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
856 dropReason = DropReason::STALE;
857 }
858 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
859 done = true;
860 break;
861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
863
864 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700866 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
Michael Wright3a981722015-06-10 15:26:13 +0100868 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869
870 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 }
873}
874
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700875/**
876 * Return true if the events preceding this incoming motion event should be dropped
877 * Return false otherwise (the default behaviour)
878 */
879bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700880 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700881 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700882
883 // Optimize case where the current application is unresponsive and the user
884 // decides to touch a window in a different application.
885 // If the application takes too long to catch up then we drop all events preceding
886 // the touch into the other window.
887 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700888 int32_t displayId = motionEntry.displayId;
889 int32_t x = static_cast<int32_t>(
890 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
891 int32_t y = static_cast<int32_t>(
892 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500893 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700894 findTouchedWindowAtLocked(displayId, x, y, nullptr);
895 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700896 touchedWindowHandle->getApplicationToken() !=
897 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700898 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 ALOGI("Pruning input queue because user touched a different application while waiting "
900 "for %s",
901 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700902 return true;
903 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700904
905 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600906 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
908 sp<Connection> connection =
909 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000910 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700911 // This monitor could take more input. Drop all events preceding this
912 // event, so that gesture monitor could get a chance to receive the stream
913 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
914 "responsive gesture monitor that may handle the event",
915 mAwaitedFocusedApplication->getName().c_str());
916 return true;
917 }
918 }
919 }
920
921 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
922 // yet been processed by some connections, the dispatcher will wait for these motion
923 // events to be processed before dispatching the key event. This is because these motion events
924 // may cause a new window to be launched, which the user might expect to receive focus.
925 // To prevent waiting forever for such events, just send the key to the currently focused window
926 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
927 ALOGD("Received a new pointer down event, stop waiting for events to process and "
928 "just send the pending key event to the focused window.");
929 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700930 }
931 return false;
932}
933
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700934bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700935 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700936 mInboundQueue.push_back(std::move(newEntry));
937 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 traceInboundQueueLengthLocked();
939
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700940 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700941 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700942 // Optimize app switch latency.
943 // If the application takes too long to catch up then we drop all events preceding
944 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700945 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700947 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700948 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700949 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700954 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 mAppSwitchSawKeyDown = false;
956 needWake = true;
957 }
958 }
959 }
960 break;
961 }
962
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700963 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700964 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
965 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700966 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100970 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700971 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
972 break;
973 }
974 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800975 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700976 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800977 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
978 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700979 // nothing to do
980 break;
981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 }
983
984 return needWake;
985}
986
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700987void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700988 // Do not store sensor event in recent queue to avoid flooding the queue.
989 if (entry->type != EventEntry::Type::SENSOR) {
990 mRecentQueue.push_back(entry);
991 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700992 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700993 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
995}
996
chaviw98318de2021-05-19 16:45:23 -0500997sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
998 int32_t y, TouchState* touchState,
999 bool addOutsideTargets,
1000 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001001 if (addOutsideTargets && touchState == nullptr) {
1002 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001005 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1006 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001007 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001008 continue;
1009 }
chaviw98318de2021-05-19 16:45:23 -05001010 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001012 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013
1014 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001015 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1016 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1017 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1019 // Found window.
1020 return windowHandle;
1021 }
1022 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001023
chaviw98318de2021-05-19 16:45:23 -05001024 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001025 touchState->addOrUpdateWindow(windowHandle,
1026 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1027 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 }
1031 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001032 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033}
1034
Garfield Tane84e6f92019-08-29 17:28:41 -07001035std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001036 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001037 std::vector<TouchedMonitor> touchedMonitors;
1038
1039 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1040 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001041 return touchedMonitors;
1042}
1043
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001044void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 const char* reason;
1046 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001047 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001049 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 reason = "inbound event was dropped because the policy consumed it";
1052 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001053 case DropReason::DISABLED:
1054 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 ALOGI("Dropped event because input dispatch is disabled.");
1056 }
1057 reason = "inbound event was dropped because input dispatch is disabled";
1058 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001059 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 ALOGI("Dropped event because of pending overdue app switch.");
1061 reason = "inbound event was dropped because of pending overdue app switch";
1062 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001063 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 ALOGI("Dropped event because the current application is not responding and the user "
1065 "has started interacting with a different application.");
1066 reason = "inbound event was dropped because the current application is not responding "
1067 "and the user has started interacting with a different application";
1068 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001069 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 ALOGI("Dropped event because it is stale.");
1071 reason = "inbound event was dropped because it is stale";
1072 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001073 case DropReason::NO_POINTER_CAPTURE:
1074 ALOGI("Dropped event because there is no window with Pointer Capture.");
1075 reason = "inbound event was dropped because there is no window with Pointer Capture";
1076 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 case DropReason::NOT_DROPPED: {
1078 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 }
1082
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001083 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001084 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1086 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001089 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001090 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1091 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1093 synthesizeCancelationEventsForAllConnectionsLocked(options);
1094 } else {
1095 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1096 synthesizeCancelationEventsForAllConnectionsLocked(options);
1097 }
1098 break;
1099 }
Chris Yef59a2f42020-10-16 12:55:26 -07001100 case EventEntry::Type::SENSOR: {
1101 break;
1102 }
arthurhungb89ccb02020-12-30 16:19:01 +08001103 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1104 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001105 break;
1106 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001107 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001108 case EventEntry::Type::CONFIGURATION_CHANGED:
1109 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001110 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001111 break;
1112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 }
1114}
1115
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001116static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1118 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119}
1120
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001121bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1122 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1123 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1124 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125}
1126
1127bool InputDispatcher::isAppSwitchPendingLocked() {
1128 return mAppSwitchDueTime != LONG_LONG_MAX;
1129}
1130
1131void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1132 mAppSwitchDueTime = LONG_LONG_MAX;
1133
1134#if DEBUG_APP_SWITCH
1135 if (handled) {
1136 ALOGD("App switch has arrived.");
1137 } else {
1138 ALOGD("App switch was abandoned.");
1139 }
1140#endif
1141}
1142
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001144 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145}
1146
1147bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001148 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 return false;
1150 }
1151
1152 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001153 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001154 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001156 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157
1158 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001159 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 return true;
1161}
1162
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001163void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1164 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165}
1166
1167void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001168 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001170 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 releaseInboundEventLocked(entry);
1172 }
1173 traceInboundQueueLengthLocked();
1174}
1175
1176void InputDispatcher::releasePendingEventLocked() {
1177 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001179 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 }
1181}
1182
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001183void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001185 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186#if DEBUG_DISPATCH_CYCLE
1187 ALOGD("Injected inbound event was dropped.");
1188#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001189 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001192 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195}
1196
1197void InputDispatcher::resetKeyRepeatLocked() {
1198 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001199 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201}
1202
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1204 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205
Michael Wright2e732952014-09-24 13:26:59 -07001206 uint32_t policyFlags = entry->policyFlags &
1207 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209 std::shared_ptr<KeyEntry> newEntry =
1210 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1211 entry->source, entry->displayId, policyFlags, entry->action,
1212 entry->flags, entry->keyCode, entry->scanCode,
1213 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 newEntry->syntheticRepeat = true;
1216 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001218 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219}
1220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001224 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225#endif
1226
1227 // Reset key repeating in case a keyboard device was added or removed or something.
1228 resetKeyRepeatLocked();
1229
1230 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001231 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1232 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001233 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001234 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 return true;
1236}
1237
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1239 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1242 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243#endif
1244
liushenxiang42232912021-05-21 20:24:09 +08001245 // Reset key repeating in case a keyboard device was disabled or enabled.
1246 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1247 resetKeyRepeatLocked();
1248 }
1249
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001250 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 synthesizeCancelationEventsForAllConnectionsLocked(options);
1253 return true;
1254}
1255
Vishnu Nairad321cd2020-08-20 16:40:21 -07001256void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001257 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001258 if (mPendingEvent != nullptr) {
1259 // Move the pending event to the front of the queue. This will give the chance
1260 // for the pending event to get dispatched to the newly focused window
1261 mInboundQueue.push_front(mPendingEvent);
1262 mPendingEvent = nullptr;
1263 }
1264
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 std::unique_ptr<FocusEntry> focusEntry =
1266 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1267 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001268
1269 // This event should go to the front of the queue, but behind all other focus events
1270 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001272 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 [](const std::shared_ptr<EventEntry>& event) {
1274 return event->type == EventEntry::Type::FOCUS;
1275 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001276
1277 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001279}
1280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001282 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001283 if (channel == nullptr) {
1284 return; // Window has gone away
1285 }
1286 InputTarget target;
1287 target.inputChannel = channel;
1288 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1289 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001290 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1291 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001292 std::string reason = std::string("reason=").append(entry->reason);
1293 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001294 dispatchEventLocked(currentTime, entry, {target});
1295}
1296
Prabir Pradhan99987712020-11-10 18:43:05 -08001297void InputDispatcher::dispatchPointerCaptureChangedLocked(
1298 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1299 DropReason& dropReason) {
1300 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001301 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1302 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1303 }
1304 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001305 // Pointer capture was already forcefully disabled because of focus change.
1306 dropReason = DropReason::NOT_DROPPED;
1307 return;
1308 }
1309
1310 // Set drop reason for early returns
1311 dropReason = DropReason::NO_POINTER_CAPTURE;
1312
1313 sp<IBinder> token;
1314 if (entry->pointerCaptureEnabled) {
1315 // Enable Pointer Capture
1316 if (!mFocusedWindowRequestedPointerCapture) {
1317 // This can happen if a window requests capture and immediately releases capture.
1318 ALOGW("No window requested Pointer Capture.");
1319 return;
1320 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001321 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001322 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1323 mWindowTokenWithPointerCapture = token;
1324 } else {
1325 // Disable Pointer Capture
1326 token = mWindowTokenWithPointerCapture;
1327 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001328 if (mFocusedWindowRequestedPointerCapture) {
1329 mFocusedWindowRequestedPointerCapture = false;
1330 setPointerCaptureLocked(false);
1331 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 }
1333
1334 auto channel = getInputChannelLocked(token);
1335 if (channel == nullptr) {
1336 // Window has gone away, clean up Pointer Capture state.
1337 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001338 if (mFocusedWindowRequestedPointerCapture) {
1339 mFocusedWindowRequestedPointerCapture = false;
1340 setPointerCaptureLocked(false);
1341 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001342 return;
1343 }
1344 InputTarget target;
1345 target.inputChannel = channel;
1346 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1347 entry->dispatchInProgress = true;
1348 dispatchEventLocked(currentTime, entry, {target});
1349
1350 dropReason = DropReason::NOT_DROPPED;
1351}
1352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001353bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 if (!entry->dispatchInProgress) {
1357 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1358 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1359 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1360 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001361 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 // We have seen two identical key downs in a row which indicates that the device
1363 // driver is automatically generating key repeats itself. We take note of the
1364 // repeat here, but we disable our own next key repeat timer since it is clear that
1365 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001366 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1367 // Make sure we don't get key down from a different device. If a different
1368 // device Id has same key pressed down, the new device Id will replace the
1369 // current one to hold the key repeat with repeat count reset.
1370 // In the future when got a KEY_UP on the device id, drop it and do not
1371 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1373 resetKeyRepeatLocked();
1374 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1375 } else {
1376 // Not a repeat. Save key down state in case we do see a repeat later.
1377 resetKeyRepeatLocked();
1378 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1379 }
1380 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001381 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1382 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001383 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001384#if DEBUG_INBOUND_EVENT_DETAILS
1385 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1386#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 resetKeyRepeatLocked();
1389 }
1390
1391 if (entry->repeatCount == 1) {
1392 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1393 } else {
1394 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1395 }
1396
1397 entry->dispatchInProgress = true;
1398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001399 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 }
1401
1402 // Handle case where the policy asked us to try again later last time.
1403 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1404 if (currentTime < entry->interceptKeyWakeupTime) {
1405 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1406 *nextWakeupTime = entry->interceptKeyWakeupTime;
1407 }
1408 return false; // wait until next wakeup
1409 }
1410 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1411 entry->interceptKeyWakeupTime = 0;
1412 }
1413
1414 // Give the policy a chance to intercept the key.
1415 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1416 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001417 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001418 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001419 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001420 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001421 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001423 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 return false; // wait for the command to run
1425 } else {
1426 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1427 }
1428 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001429 if (*dropReason == DropReason::NOT_DROPPED) {
1430 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 }
1432 }
1433
1434 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001435 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001436 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1438 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001439 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 return true;
1441 }
1442
1443 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001444 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001445 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001446 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001447 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 return false;
1449 }
1450
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001451 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001452 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 return true;
1454 }
1455
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001456 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001457 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
1459 // Dispatch the key.
1460 dispatchEventLocked(currentTime, entry, inputTargets);
1461 return true;
1462}
1463
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001464void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001466 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001467 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1468 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001469 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1470 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1471 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472#endif
1473}
1474
Chris Yef59a2f42020-10-16 12:55:26 -07001475void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1476 mLock.unlock();
1477
1478 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1479 if (entry->accuracyChanged) {
1480 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1481 }
1482 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1483 entry->hwTimestamp, entry->values);
1484 mLock.lock();
1485}
1486
1487void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1488 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1489#if DEBUG_OUTBOUND_EVENT_DETAILS
1490 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1491 "source=0x%x, sensorType=%s",
1492 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001493 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001494#endif
1495 std::unique_ptr<CommandEntry> commandEntry =
1496 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1497 commandEntry->sensorEntry = entry;
1498 postCommandLocked(std::move(commandEntry));
1499}
1500
1501bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1502#if DEBUG_OUTBOUND_EVENT_DETAILS
1503 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1504 NamedEnum::string(sensorType).c_str());
1505#endif
1506 { // acquire lock
1507 std::scoped_lock _l(mLock);
1508
1509 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1510 std::shared_ptr<EventEntry> entry = *it;
1511 if (entry->type == EventEntry::Type::SENSOR) {
1512 it = mInboundQueue.erase(it);
1513 releaseInboundEventLocked(entry);
1514 }
1515 }
1516 }
1517 return true;
1518}
1519
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001521 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001522 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001524 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 entry->dispatchInProgress = true;
1526
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001527 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 }
1529
1530 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001531 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001532 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001533 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1534 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 return true;
1536 }
1537
1538 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1539
1540 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001541 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542
1543 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001544 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 if (isPointerEvent) {
1546 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001547 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001548 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001549 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 } else {
1551 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001552 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001553 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 return false;
1557 }
1558
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001559 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001561 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1562 return true;
1563 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001565 CancelationOptions::Mode mode(isPointerEvent
1566 ? CancelationOptions::CANCEL_POINTER_EVENTS
1567 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1568 CancelationOptions options(mode, "input event injection failed");
1569 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return true;
1571 }
1572
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001573 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001574 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575
1576 // Dispatch the motion.
1577 if (conflictingPointerActions) {
1578 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 synthesizeCancelationEventsForAllConnectionsLocked(options);
1581 }
1582 dispatchEventLocked(currentTime, entry, inputTargets);
1583 return true;
1584}
1585
chaviw98318de2021-05-19 16:45:23 -05001586void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001587 bool isExiting, const MotionEntry& motionEntry) {
1588 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1589 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1590 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1591 PointerCoords pointerCoords;
1592 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1593 pointerCoords.transform(windowHandle->getInfo()->transform);
1594
1595 std::unique_ptr<DragEntry> dragEntry =
1596 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1597 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1598 pointerCoords.getY());
1599
1600 enqueueInboundEventLocked(std::move(dragEntry));
1601}
1602
1603void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1604 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1605 if (channel == nullptr) {
1606 return; // Window has gone away
1607 }
1608 InputTarget target;
1609 target.inputChannel = channel;
1610 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1611 entry->dispatchInProgress = true;
1612 dispatchEventLocked(currentTime, entry, {target});
1613}
1614
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001615void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001617 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 ", policyFlags=0x%x, "
1619 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1620 "metaState=0x%x, buttonState=0x%x,"
1621 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001622 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1623 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1624 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001626 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001628 "x=%f, y=%f, pressure=%f, size=%f, "
1629 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1630 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001631 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1632 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1633 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1634 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1635 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1636 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1637 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1638 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1639 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1640 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
1642#endif
1643}
1644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001645void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1646 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001648 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649#if DEBUG_DISPATCH_CYCLE
1650 ALOGD("dispatchEventToCurrentInputTargets");
1651#endif
1652
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001653 updateInteractionTokensLocked(*eventEntry, inputTargets);
1654
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1656
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001659 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001660 sp<Connection> connection =
1661 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001662 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001663 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001665 if (DEBUG_FOCUS) {
1666 ALOGD("Dropping event delivery to target with channel '%s' because it "
1667 "is no longer registered with the input dispatcher.",
1668 inputTarget.inputChannel->getName().c_str());
1669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 }
1671 }
1672}
1673
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001674void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1675 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1676 // If the policy decides to close the app, we will get a channel removal event via
1677 // unregisterInputChannel, and will clean up the connection that way. We are already not
1678 // sending new pointers to the connection when it blocked, but focused events will continue to
1679 // pile up.
1680 ALOGW("Canceling events for %s because it is unresponsive",
1681 connection->inputChannel->getName().c_str());
1682 if (connection->status == Connection::STATUS_NORMAL) {
1683 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1684 "application not responding");
1685 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 }
1687}
1688
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001689void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001690 if (DEBUG_FOCUS) {
1691 ALOGD("Resetting ANR timeouts.");
1692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693
1694 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001695 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001696 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697}
1698
Tiger Huang721e26f2018-07-24 22:26:19 +08001699/**
1700 * Get the display id that the given event should go to. If this event specifies a valid display id,
1701 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1702 * Focused display is the display that the user most recently interacted with.
1703 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001704int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001705 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001706 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001707 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001708 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1709 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 break;
1711 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001712 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001713 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1714 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001715 break;
1716 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001717 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001718 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001719 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001720 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001721 case EventEntry::Type::SENSOR:
1722 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001723 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001724 return ADISPLAY_ID_NONE;
1725 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001726 }
1727 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1728}
1729
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001730bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1731 const char* focusedWindowName) {
1732 if (mAnrTracker.empty()) {
1733 // already processed all events that we waited for
1734 mKeyIsWaitingForEventsTimeout = std::nullopt;
1735 return false;
1736 }
1737
1738 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1739 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001740 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001741 mKeyIsWaitingForEventsTimeout = currentTime +
1742 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1743 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001744 return true;
1745 }
1746
1747 // We still have pending events, and already started the timer
1748 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1749 return true; // Still waiting
1750 }
1751
1752 // Waited too long, and some connection still hasn't processed all motions
1753 // Just send the key to the focused window
1754 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1755 focusedWindowName);
1756 mKeyIsWaitingForEventsTimeout = std::nullopt;
1757 return false;
1758}
1759
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001760InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1761 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1762 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001763 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764
Tiger Huang721e26f2018-07-24 22:26:19 +08001765 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001766 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001767 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001768 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1769
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 // If there is no currently focused window and no focused application
1771 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1773 ALOGI("Dropping %s event because there is no focused window or focused application in "
1774 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001775 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001776 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
1778
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001779 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1780 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1781 // start interacting with another application via touch (app switch). This code can be removed
1782 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1783 // an app is expected to have a focused window.
1784 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1785 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1786 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001787 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1788 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1789 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001790 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001791 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001792 ALOGW("Waiting because no window has focus but %s may eventually add a "
1793 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001794 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001795 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001796 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1798 // Already raised ANR. Drop the event
1799 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001800 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001801 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001802 } else {
1803 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001805 }
1806 }
1807
1808 // we have a valid, non-null focused window
1809 resetNoFocusedWindowTimeoutLocked();
1810
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 }
1815
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001816 if (focusedWindowHandle->getInfo()->paused) {
1817 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001818 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001819 }
1820
1821 // If the event is a key event, then we must wait for all previous events to
1822 // complete before delivering it because previous events may have the
1823 // side-effect of transferring focus to a different window and we want to
1824 // ensure that the following keys are sent to the new window.
1825 //
1826 // Suppose the user touches a button in a window then immediately presses "A".
1827 // If the button causes a pop-up window to appear then we want to ensure that
1828 // the "A" key is delivered to the new pop-up window. This is because users
1829 // often anticipate pending UI changes when typing on a keyboard.
1830 // To obtain this behavior, we must serialize key events with respect to all
1831 // prior input events.
1832 if (entry.type == EventEntry::Type::KEY) {
1833 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1834 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 }
1838
1839 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001840 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001841 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1842 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843
1844 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846}
1847
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001848/**
1849 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1850 * that are currently unresponsive.
1851 */
1852std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1853 const std::vector<TouchedMonitor>& monitors) const {
1854 std::vector<TouchedMonitor> responsiveMonitors;
1855 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1856 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1857 sp<Connection> connection = getConnectionLocked(
1858 monitor.monitor.inputChannel->getConnectionToken());
1859 if (connection == nullptr) {
1860 ALOGE("Could not find connection for monitor %s",
1861 monitor.monitor.inputChannel->getName().c_str());
1862 return false;
1863 }
1864 if (!connection->responsive) {
1865 ALOGW("Unresponsive monitor %s will not get the new gesture",
1866 connection->inputChannel->getName().c_str());
1867 return false;
1868 }
1869 return true;
1870 });
1871 return responsiveMonitors;
1872}
1873
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1875 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1876 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001877 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 enum InjectionPermission {
1879 INJECTION_PERMISSION_UNKNOWN,
1880 INJECTION_PERMISSION_GRANTED,
1881 INJECTION_PERMISSION_DENIED
1882 };
1883
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 // For security reasons, we defer updating the touch state until we are sure that
1885 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001886 int32_t displayId = entry.displayId;
1887 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1889
1890 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001891 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001893 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1894 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001896 // Copy current touch state into tempTouchState.
1897 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1898 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001899 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001900 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001901 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1902 mTouchStatesByDisplay.find(displayId);
1903 if (oldStateIt != mTouchStatesByDisplay.end()) {
1904 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001905 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001906 }
1907
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001908 bool isSplit = tempTouchState.split;
1909 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1910 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1911 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001912 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1913 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1914 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1915 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1916 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001917 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 bool wrongDevice = false;
1919 if (newGesture) {
1920 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001921 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001922 ALOGI("Dropping event because a pointer for a different device is already down "
1923 "in display %" PRId32,
1924 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001925 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001926 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 switchedDevice = false;
1928 wrongDevice = true;
1929 goto Failed;
1930 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001931 tempTouchState.reset();
1932 tempTouchState.down = down;
1933 tempTouchState.deviceId = entry.deviceId;
1934 tempTouchState.source = entry.source;
1935 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001937 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001938 ALOGI("Dropping move event because a pointer for a different device is already active "
1939 "in display %" PRId32,
1940 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001941 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001943 switchedDevice = false;
1944 wrongDevice = true;
1945 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 }
1947
1948 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1949 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1950
Garfield Tan00f511d2019-06-12 16:55:40 -07001951 int32_t x;
1952 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001954 // Always dispatch mouse events to cursor position.
1955 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001956 x = int32_t(entry.xCursorPosition);
1957 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001958 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001959 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1960 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001961 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001962 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001963 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1964 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001965
1966 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001967 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00001968 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001971 if (newTouchedWindowHandle != nullptr &&
1972 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001973 // New window supports splitting, but we should never split mouse events.
1974 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 } else if (isSplit) {
1976 // New window does not support splitting but we have already split events.
1977 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001978 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 }
1980
1981 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001982 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001984 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001985 }
1986
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1988 ALOGI("Not sending touch event to %s because it is paused",
1989 newTouchedWindowHandle->getName().c_str());
1990 newTouchedWindowHandle = nullptr;
1991 }
1992
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001993 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001995 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1996 if (!isResponsive) {
1997 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001998 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1999 newTouchedWindowHandle = nullptr;
2000 }
2001 }
2002
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002003 // Drop events that can't be trusted due to occlusion
2004 if (newTouchedWindowHandle != nullptr &&
2005 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2006 TouchOcclusionInfo occlusionInfo =
2007 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002008 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002009 if (DEBUG_TOUCH_OCCLUSION) {
2010 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2011 for (const auto& log : occlusionInfo.debugInfo) {
2012 ALOGD("%s", log.c_str());
2013 }
2014 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002015 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2016 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2017 ALOGW("Dropping untrusted touch event due to %s/%d",
2018 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2019 newTouchedWindowHandle = nullptr;
2020 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002021 }
2022 }
2023
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 // Also don't send the new touch event to unresponsive gesture monitors
2025 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2026
Michael Wright3dd60e22019-03-27 22:06:44 +00002027 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2028 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002029 "(%d, %d) in display %" PRId32 ".",
2030 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002031 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002032 goto Failed;
2033 }
2034
2035 if (newTouchedWindowHandle != nullptr) {
2036 // Set target flags.
2037 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2038 if (isSplit) {
2039 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002041 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2042 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2043 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2044 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2045 }
2046
2047 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002048 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2049 newHoverWindowHandle = nullptr;
2050 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002051 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002052 }
2053
2054 // Update the temporary touch state.
2055 BitSet32 pointerIds;
2056 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002057 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002058 pointerIds.markBit(pointerId);
2059 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002060 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 }
2062
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002063 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 } else {
2065 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2066
2067 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002068 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002069 if (DEBUG_FOCUS) {
2070 ALOGD("Dropping event because the pointer is not down or we previously "
2071 "dropped the pointer down event in display %" PRId32,
2072 displayId);
2073 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002074 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 goto Failed;
2076 }
2077
arthurhung6d4bed92021-03-17 11:59:33 +08002078 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002079
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002081 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002082 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002083 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2084 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
chaviw98318de2021-05-19 16:45:23 -05002086 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002088 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2090 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002091 if (DEBUG_FOCUS) {
2092 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2093 oldTouchedWindowHandle->getName().c_str(),
2094 newTouchedWindowHandle->getName().c_str(), displayId);
2095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002097 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2098 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2099 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100
2101 // Make a slippery entrance into the new window.
2102 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2103 isSplit = true;
2104 }
2105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002106 int32_t targetFlags =
2107 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 if (isSplit) {
2109 targetFlags |= InputTarget::FLAG_SPLIT;
2110 }
2111 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2112 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002113 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2114 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 }
2116
2117 BitSet32 pointerIds;
2118 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002119 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002121 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 }
2123 }
2124 }
2125
2126 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002127 // Let the previous window know that the hover sequence is over, unless we already did it
2128 // when dispatching it as is to newTouchedWindowHandle.
2129 if (mLastHoverWindowHandle != nullptr &&
2130 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2131 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132#if DEBUG_HOVER
2133 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002134 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002136 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2137 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
2139
Garfield Tandf26e862020-07-01 20:18:19 -07002140 // Let the new window know that the hover sequence is starting, unless we already did it
2141 // when dispatching it as is to newTouchedWindowHandle.
2142 if (newHoverWindowHandle != nullptr &&
2143 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2144 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145#if DEBUG_HOVER
2146 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002147 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002149 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2150 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2151 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153 }
2154
2155 // Check permission to inject into all touched foreground windows and ensure there
2156 // is at least one touched foreground window.
2157 {
2158 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002159 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2161 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002162 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002163 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 injectionPermission = INJECTION_PERMISSION_DENIED;
2165 goto Failed;
2166 }
2167 }
2168 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002169 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002170 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002171 ALOGI("Dropping event because there is no touched foreground window in display "
2172 "%" PRId32 " or gesture monitor to receive it.",
2173 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002174 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 goto Failed;
2176 }
2177
2178 // Permission granted to injection into all touched foreground windows.
2179 injectionPermission = INJECTION_PERMISSION_GRANTED;
2180 }
2181
2182 // Check whether windows listening for outside touches are owned by the same UID. If it is
2183 // set the policy flag that we will not reveal coordinate information to this window.
2184 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002185 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002186 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002187 if (foregroundWindowHandle) {
2188 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002190 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002191 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2192 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2193 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 InputTarget::FLAG_ZERO_COORDS,
2195 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198 }
2199 }
2200 }
2201
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 // If this is the first pointer going down and the touched window has a wallpaper
2203 // then also add the touched wallpaper windows so they are locked in for the duration
2204 // of the touch gesture.
2205 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2206 // engine only supports touch events. We would need to add a mechanism similar
2207 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2208 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002209 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002210 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002211 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002212 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002213 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002214 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2215 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002216 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002217 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 .addOrUpdateWindow(windowHandle,
2220 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2221 InputTarget::
2222 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2223 InputTarget::FLAG_DISPATCH_AS_IS,
2224 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226 }
2227 }
2228 }
2229
2230 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002231 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002233 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002235 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002238 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002239 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002240 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002241 }
2242
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 // Drop the outside or hover touch windows since we will not care about them
2244 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002245 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
2247Failed:
2248 // Check injection permission once and for all.
2249 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002250 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 injectionPermission = INJECTION_PERMISSION_GRANTED;
2252 } else {
2253 injectionPermission = INJECTION_PERMISSION_DENIED;
2254 }
2255 }
2256
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002257 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2258 return injectionResult;
2259 }
2260
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002262 if (!wrongDevice) {
2263 if (switchedDevice) {
2264 if (DEBUG_FOCUS) {
2265 ALOGD("Conflicting pointer actions: Switched to a different device.");
2266 }
2267 *outConflictingPointerActions = true;
2268 }
2269
2270 if (isHoverAction) {
2271 // Started hovering, therefore no longer down.
2272 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002273 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002274 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2275 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 *outConflictingPointerActions = true;
2278 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002279 tempTouchState.reset();
2280 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2281 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2282 tempTouchState.deviceId = entry.deviceId;
2283 tempTouchState.source = entry.source;
2284 tempTouchState.displayId = displayId;
2285 }
2286 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2287 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2288 // All pointers up or canceled.
2289 tempTouchState.reset();
2290 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2291 // First pointer went down.
2292 if (oldState && oldState->down) {
2293 if (DEBUG_FOCUS) {
2294 ALOGD("Conflicting pointer actions: Down received while already down.");
2295 }
2296 *outConflictingPointerActions = true;
2297 }
2298 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2299 // One pointer went up.
2300 if (isSplit) {
2301 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2302 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002304 for (size_t i = 0; i < tempTouchState.windows.size();) {
2305 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2306 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2307 touchedWindow.pointerIds.clearBit(pointerId);
2308 if (touchedWindow.pointerIds.isEmpty()) {
2309 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2310 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002313 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002315 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002316 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002317
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002318 // Save changes unless the action was scroll in which case the temporary touch
2319 // state was only valid for this one action.
2320 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2321 if (tempTouchState.displayId >= 0) {
2322 mTouchStatesByDisplay[displayId] = tempTouchState;
2323 } else {
2324 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002328 // Update hover state.
2329 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
2331
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 return injectionResult;
2333}
2334
arthurhung6d4bed92021-03-17 11:59:33 +08002335void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002336 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002337 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002338 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002339 if (dropWindow) {
2340 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2341 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002342 } else {
2343 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002344 }
2345 mDragState.reset();
2346}
2347
2348void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2349 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002350 return;
2351 }
2352
arthurhung6d4bed92021-03-17 11:59:33 +08002353 if (!mDragState->isStartDrag) {
2354 mDragState->isStartDrag = true;
2355 mDragState->isStylusButtonDownAtStart =
2356 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2357 }
2358
arthurhungb89ccb02020-12-30 16:19:01 +08002359 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2360 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2361 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2362 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002363 // Handle the special case : stylus button no longer pressed.
2364 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2365 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2366 finishDragAndDrop(entry.displayId, x, y);
2367 return;
2368 }
2369
chaviw98318de2021-05-19 16:45:23 -05002370 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002371 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002372 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002373 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002374 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2375 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2376 if (mDragState->dragHoverWindowHandle != nullptr) {
2377 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2378 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002379 }
arthurhung6d4bed92021-03-17 11:59:33 +08002380 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002381 }
2382 // enqueue drag location if needed.
2383 if (hoverWindowHandle != nullptr) {
2384 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2385 }
arthurhung6d4bed92021-03-17 11:59:33 +08002386 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2387 finishDragAndDrop(entry.displayId, x, y);
2388 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002389 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002390 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002391 }
2392}
2393
chaviw98318de2021-05-19 16:45:23 -05002394void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002395 int32_t targetFlags, BitSet32 pointerIds,
2396 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002397 std::vector<InputTarget>::iterator it =
2398 std::find_if(inputTargets.begin(), inputTargets.end(),
2399 [&windowHandle](const InputTarget& inputTarget) {
2400 return inputTarget.inputChannel->getConnectionToken() ==
2401 windowHandle->getToken();
2402 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002403
chaviw98318de2021-05-19 16:45:23 -05002404 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002405
2406 if (it == inputTargets.end()) {
2407 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002408 std::shared_ptr<InputChannel> inputChannel =
2409 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002410 if (inputChannel == nullptr) {
2411 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2412 return;
2413 }
2414 inputTarget.inputChannel = inputChannel;
2415 inputTarget.flags = targetFlags;
2416 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002417 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002418 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002419 inputTargets.push_back(inputTarget);
2420 it = inputTargets.end() - 1;
2421 }
2422
2423 ALOG_ASSERT(it->flags == targetFlags);
2424 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2425
chaviw1ff3d1e2020-07-01 15:53:47 -07002426 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427}
2428
Michael Wright3dd60e22019-03-27 22:06:44 +00002429void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 int32_t displayId, float xOffset,
2431 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002432 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2433 mGlobalMonitorsByDisplay.find(displayId);
2434
2435 if (it != mGlobalMonitorsByDisplay.end()) {
2436 const std::vector<Monitor>& monitors = it->second;
2437 for (const Monitor& monitor : monitors) {
2438 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441}
2442
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002443void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2444 float yOffset,
2445 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002446 InputTarget target;
2447 target.inputChannel = monitor.inputChannel;
2448 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002449 ui::Transform t;
2450 t.set(xOffset, yOffset);
2451 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002452 inputTargets.push_back(target);
2453}
2454
chaviw98318de2021-05-19 16:45:23 -05002455bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 const InjectionState* injectionState) {
2457 if (injectionState &&
2458 (windowHandle == nullptr ||
2459 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2460 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002461 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 "owned by uid %d",
2464 injectionState->injectorPid, injectionState->injectorUid,
2465 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 } else {
2467 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002468 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470 return false;
2471 }
2472 return true;
2473}
2474
Robert Carrc9bf1d32020-04-13 17:21:08 -07002475/**
2476 * Indicate whether one window handle should be considered as obscuring
2477 * another window handle. We only check a few preconditions. Actually
2478 * checking the bounds is left to the caller.
2479 */
chaviw98318de2021-05-19 16:45:23 -05002480static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2481 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002482 // Compare by token so cloned layers aren't counted
2483 if (haveSameToken(windowHandle, otherHandle)) {
2484 return false;
2485 }
2486 auto info = windowHandle->getInfo();
2487 auto otherInfo = otherHandle->getInfo();
2488 if (!otherInfo->visible) {
2489 return false;
chaviw98318de2021-05-19 16:45:23 -05002490 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002491 // Those act as if they were invisible, so we don't need to flag them.
2492 // We do want to potentially flag touchable windows even if they have 0
2493 // opacity, since they can consume touches and alter the effects of the
2494 // user interaction (eg. apps that rely on
2495 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2496 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2497 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002498 } else if (info->ownerUid == otherInfo->ownerUid) {
2499 // If ownerUid is the same we don't generate occlusion events as there
2500 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002501 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002502 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002503 return false;
2504 } else if (otherInfo->displayId != info->displayId) {
2505 return false;
2506 }
2507 return true;
2508}
2509
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002510/**
2511 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2512 * untrusted, one should check:
2513 *
2514 * 1. If result.hasBlockingOcclusion is true.
2515 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2516 * BLOCK_UNTRUSTED.
2517 *
2518 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2519 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2520 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2521 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2522 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2523 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2524 *
2525 * If neither of those is true, then it means the touch can be allowed.
2526 */
2527InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002528 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2529 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002530 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002531 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002532 TouchOcclusionInfo info;
2533 info.hasBlockingOcclusion = false;
2534 info.obscuringOpacity = 0;
2535 info.obscuringUid = -1;
2536 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002537 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002538 if (windowHandle == otherHandle) {
2539 break; // All future windows are below us. Exit early.
2540 }
chaviw98318de2021-05-19 16:45:23 -05002541 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002542 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2543 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002544 if (DEBUG_TOUCH_OCCLUSION) {
2545 info.debugInfo.push_back(
2546 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2547 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002548 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2549 // we perform the checks below to see if the touch can be propagated or not based on the
2550 // window's touch occlusion mode
2551 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2552 info.hasBlockingOcclusion = true;
2553 info.obscuringUid = otherInfo->ownerUid;
2554 info.obscuringPackage = otherInfo->packageName;
2555 break;
2556 }
2557 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2558 uint32_t uid = otherInfo->ownerUid;
2559 float opacity =
2560 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2561 // Given windows A and B:
2562 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2563 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2564 opacityByUid[uid] = opacity;
2565 if (opacity > info.obscuringOpacity) {
2566 info.obscuringOpacity = opacity;
2567 info.obscuringUid = uid;
2568 info.obscuringPackage = otherInfo->packageName;
2569 }
2570 }
2571 }
2572 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002573 if (DEBUG_TOUCH_OCCLUSION) {
2574 info.debugInfo.push_back(
2575 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2576 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002577 return info;
2578}
2579
chaviw98318de2021-05-19 16:45:23 -05002580std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002581 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002582 return StringPrintf(INDENT2
2583 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2584 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2585 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2586 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002587 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002588 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002589 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002590 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2591 info->frameTop, info->frameRight, info->frameBottom,
2592 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002593 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2594 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2595 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002596}
2597
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002598bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2599 if (occlusionInfo.hasBlockingOcclusion) {
2600 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2601 occlusionInfo.obscuringUid);
2602 return false;
2603 }
2604 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2605 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2606 "%.2f, maximum allowed = %.2f)",
2607 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2608 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2609 return false;
2610 }
2611 return true;
2612}
2613
chaviw98318de2021-05-19 16:45:23 -05002614bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002615 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002617 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2618 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002619 if (windowHandle == otherHandle) {
2620 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
chaviw98318de2021-05-19 16:45:23 -05002622 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002623 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002624 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 return true;
2626 }
2627 }
2628 return false;
2629}
2630
chaviw98318de2021-05-19 16:45:23 -05002631bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002632 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002633 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2634 const WindowInfo* windowInfo = windowHandle->getInfo();
2635 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002636 if (windowHandle == otherHandle) {
2637 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002638 }
chaviw98318de2021-05-19 16:45:23 -05002639 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002640 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002641 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002642 return true;
2643 }
2644 }
2645 return false;
2646}
2647
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002648std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002649 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002650 if (applicationHandle != nullptr) {
2651 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002652 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 } else {
2654 return applicationHandle->getName();
2655 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002656 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002657 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002659 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 }
2661}
2662
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002663void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002664 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002665 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2666 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002667 // Focus or pointer capture changed events are passed to apps, but do not represent user
2668 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002669 return;
2670 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002671 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002672 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002673 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002674 const WindowInfo* info = focusedWindowHandle->getInfo();
2675 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002677 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678#endif
2679 return;
2680 }
2681 }
2682
2683 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002684 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002685 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002686 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2687 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002688 return;
2689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002691 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 eventType = USER_ACTIVITY_EVENT_TOUCH;
2693 }
2694 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002696 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002697 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2698 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002699 return;
2700 }
2701 eventType = USER_ACTIVITY_EVENT_BUTTON;
2702 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002704 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002705 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002706 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002707 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002708 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2709 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002710 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002711 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002712 break;
2713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 }
2715
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002716 std::unique_ptr<CommandEntry> commandEntry =
2717 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002718 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002720 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002721 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722}
2723
2724void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002726 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002727 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002728 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002730 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002731 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002732 ATRACE_NAME(message.c_str());
2733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734#if DEBUG_DISPATCH_CYCLE
2735 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002736 "globalScaleFactor=%f, pointerIds=0x%x %s",
2737 connection->getInputChannelName().c_str(), inputTarget.flags,
2738 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2739 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740#endif
2741
2742 // Skip this event if the connection status is not normal.
2743 // We don't want to enqueue additional outbound events if the connection is broken.
2744 if (connection->status != Connection::STATUS_NORMAL) {
2745#if DEBUG_DISPATCH_CYCLE
2746 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748#endif
2749 return;
2750 }
2751
2752 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002753 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2754 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2755 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002756 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002758 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002759 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002760 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002761 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 if (!splitMotionEntry) {
2763 return; // split event was dropped
2764 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002765 if (DEBUG_FOCUS) {
2766 ALOGD("channel '%s' ~ Split motion event.",
2767 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002768 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002769 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002770 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2771 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 return;
2773 }
2774 }
2775
2776 // Not splitting. Enqueue dispatch entries for the event as is.
2777 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2778}
2779
2780void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002782 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002783 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002784 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002786 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002787 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002788 ATRACE_NAME(message.c_str());
2789 }
2790
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002791 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792
2793 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002794 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002795 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002796 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002797 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002798 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002799 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002800 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002802 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002803 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002804 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806
2807 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002808 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 startDispatchCycleLocked(currentTime, connection);
2810 }
2811}
2812
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002813void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002814 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002815 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002816 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002817 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2819 connection->getInputChannelName().c_str(),
2820 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002821 ATRACE_NAME(message.c_str());
2822 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002823 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 if (!(inputTargetFlags & dispatchMode)) {
2825 return;
2826 }
2827 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2828
2829 // This is a new event.
2830 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002831 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002832 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002834 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2835 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002836 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002838 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002839 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002840 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002841 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002842 dispatchEntry->resolvedAction = keyEntry.action;
2843 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2846 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2849 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851 return; // skip the inconsistent event
2852 }
2853 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002856 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002857 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002858 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2859 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2860 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2861 static_cast<int32_t>(IdGenerator::Source::OTHER);
2862 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002863 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2864 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2865 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2866 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2867 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2868 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2869 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2870 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2871 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2872 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2873 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002874 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002875 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002876 }
2877 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002878 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2879 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2882 "event",
2883 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002885 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2886 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002887 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002890 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2892 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2893 }
2894 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2895 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2899 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2902 "event",
2903 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 return; // skip the inconsistent event
2906 }
2907
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002908 dispatchEntry->resolvedEventId =
2909 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2910 ? mIdGenerator.nextId()
2911 : motionEntry.id;
2912 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2913 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2914 ") to MotionEvent(id=0x%" PRIx32 ").",
2915 motionEntry.id, dispatchEntry->resolvedEventId);
2916 ATRACE_NAME(message.c_str());
2917 }
2918
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002919 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2920 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2921 // Skip reporting pointer down outside focus to the policy.
2922 break;
2923 }
2924
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002925 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002926 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927
2928 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002930 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002931 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2932 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002933 break;
2934 }
Chris Yef59a2f42020-10-16 12:55:26 -07002935 case EventEntry::Type::SENSOR: {
2936 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2937 break;
2938 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002939 case EventEntry::Type::CONFIGURATION_CHANGED:
2940 case EventEntry::Type::DEVICE_RESET: {
2941 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002942 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002943 break;
2944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 }
2946
2947 // Remember that we are waiting for this dispatch to complete.
2948 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002949 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 }
2951
2952 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002953 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002954 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002955}
2956
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002957/**
2958 * This function is purely for debugging. It helps us understand where the user interaction
2959 * was taking place. For example, if user is touching launcher, we will see a log that user
2960 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2961 * We will see both launcher and wallpaper in that list.
2962 * Once the interaction with a particular set of connections starts, no new logs will be printed
2963 * until the set of interacted connections changes.
2964 *
2965 * The following items are skipped, to reduce the logspam:
2966 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2967 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2968 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2969 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2970 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002971 */
2972void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2973 const std::vector<InputTarget>& targets) {
2974 // Skip ACTION_UP events, and all events other than keys and motions
2975 if (entry.type == EventEntry::Type::KEY) {
2976 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2977 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2978 return;
2979 }
2980 } else if (entry.type == EventEntry::Type::MOTION) {
2981 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2982 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2983 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2984 return;
2985 }
2986 } else {
2987 return; // Not a key or a motion
2988 }
2989
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07002990 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002991 std::vector<sp<Connection>> newConnections;
2992 for (const InputTarget& target : targets) {
2993 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2994 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2995 continue; // Skip windows that receive ACTION_OUTSIDE
2996 }
2997
2998 sp<IBinder> token = target.inputChannel->getConnectionToken();
2999 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003000 if (connection == nullptr) {
3001 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003002 }
3003 newConnectionTokens.insert(std::move(token));
3004 newConnections.emplace_back(connection);
3005 }
3006 if (newConnectionTokens == mInteractionConnectionTokens) {
3007 return; // no change
3008 }
3009 mInteractionConnectionTokens = newConnectionTokens;
3010
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003011 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003012 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003013 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003014 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003015 std::string message = "Interaction with: " + targetList;
3016 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003017 message += "<none>";
3018 }
3019 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3020}
3021
chaviwfd6d3512019-03-25 13:23:49 -07003022void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003023 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003024 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003025 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3026 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003027 return;
3028 }
3029
Vishnu Nairc519ff72021-01-21 08:23:08 -08003030 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003031 if (focusedToken == token) {
3032 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003033 return;
3034 }
3035
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003036 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3037 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003038 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003039 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040}
3041
3042void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003043 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003044 if (ATRACE_ENABLED()) {
3045 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003047 ATRACE_NAME(message.c_str());
3048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051#endif
3052
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003053 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3054 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003056 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003057 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003058 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059
3060 // Publish the event.
3061 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003062 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3063 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003064 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003065 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3066 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003068 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003069 status = connection->inputPublisher
3070 .publishKeyEvent(dispatchEntry->seq,
3071 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3072 keyEntry.source, keyEntry.displayId,
3073 std::move(hmac), dispatchEntry->resolvedAction,
3074 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3075 keyEntry.scanCode, keyEntry.metaState,
3076 keyEntry.repeatCount, keyEntry.downTime,
3077 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003078 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 }
3080
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003081 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003082 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003085 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086
chaviw82357092020-01-28 13:13:06 -08003087 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003088 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3090 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003091 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003092 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3093 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003094 // Don't apply window scale here since we don't want scale to affect raw
3095 // coordinates. The scale will be sent back to the client and applied
3096 // later when requesting relative coordinates.
3097 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3098 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 }
3100 usingCoords = scaledCoords;
3101 }
3102 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 // We don't want the dispatch target to know.
3104 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 scaledCoords[i].clear();
3107 }
3108 usingCoords = scaledCoords;
3109 }
3110 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003111
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003112 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113
3114 // Publish the motion event.
3115 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003116 .publishMotionEvent(dispatchEntry->seq,
3117 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003118 motionEntry.deviceId, motionEntry.source,
3119 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003120 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003121 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003123 motionEntry.edgeFlags, motionEntry.metaState,
3124 motionEntry.buttonState,
3125 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003126 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003127 motionEntry.xPrecision, motionEntry.yPrecision,
3128 motionEntry.xCursorPosition,
3129 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003130 dispatchEntry->displaySize.x,
3131 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003132 motionEntry.downTime, motionEntry.eventTime,
3133 motionEntry.pointerCount,
3134 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 break;
3136 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003137
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003138 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003139 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003140 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003141 focusEntry.id,
3142 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003143 mInTouchMode);
3144 break;
3145 }
3146
Prabir Pradhan99987712020-11-10 18:43:05 -08003147 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3148 const auto& captureEntry =
3149 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3150 status = connection->inputPublisher
3151 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3152 captureEntry.pointerCaptureEnabled);
3153 break;
3154 }
3155
arthurhungb89ccb02020-12-30 16:19:01 +08003156 case EventEntry::Type::DRAG: {
3157 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3158 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3159 dragEntry.id, dragEntry.x,
3160 dragEntry.y,
3161 dragEntry.isExiting);
3162 break;
3163 }
3164
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003165 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003166 case EventEntry::Type::DEVICE_RESET:
3167 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003168 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003169 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 }
3173
3174 // Check the result.
3175 if (status) {
3176 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003177 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 "This is unexpected because the wait queue is empty, so the pipe "
3180 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003181 "event to it, status=%s(%d)",
3182 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3183 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3185 } else {
3186 // Pipe is full and we are waiting for the app to finish process some events
3187 // before sending more events to it.
3188#if DEBUG_DISPATCH_CYCLE
3189 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 "waiting for the application to catch up",
3191 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193 }
3194 } else {
3195 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003196 "status=%s(%d)",
3197 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3198 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3200 }
3201 return;
3202 }
3203
3204 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003205 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3206 connection->outboundQueue.end(),
3207 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003208 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003209 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003210 if (connection->responsive) {
3211 mAnrTracker.insert(dispatchEntry->timeoutTime,
3212 connection->inputChannel->getConnectionToken());
3213 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003214 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 }
3216}
3217
chaviw09c8d2d2020-08-24 15:48:26 -07003218std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3219 size_t size;
3220 switch (event.type) {
3221 case VerifiedInputEvent::Type::KEY: {
3222 size = sizeof(VerifiedKeyEvent);
3223 break;
3224 }
3225 case VerifiedInputEvent::Type::MOTION: {
3226 size = sizeof(VerifiedMotionEvent);
3227 break;
3228 }
3229 }
3230 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3231 return mHmacKeyManager.sign(start, size);
3232}
3233
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003234const std::array<uint8_t, 32> InputDispatcher::getSignature(
3235 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3236 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3237 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3238 // Only sign events up and down events as the purely move events
3239 // are tied to their up/down counterparts so signing would be redundant.
3240 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3241 verifiedEvent.actionMasked = actionMasked;
3242 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003243 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003244 }
3245 return INVALID_HMAC;
3246}
3247
3248const std::array<uint8_t, 32> InputDispatcher::getSignature(
3249 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3250 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3251 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3252 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003253 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003254}
3255
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003258 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259#if DEBUG_DISPATCH_CYCLE
3260 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262#endif
3263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 if (connection->status == Connection::STATUS_BROKEN ||
3265 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 return;
3267 }
3268
3269 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003270 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271}
3272
3273void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 const sp<Connection>& connection,
3275 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276#if DEBUG_DISPATCH_CYCLE
3277 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003278 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279#endif
3280
3281 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003282 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003283 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003284 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003285 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286
3287 // The connection appears to be unrecoverably broken.
3288 // Ignore already broken or zombie connections.
3289 if (connection->status == Connection::STATUS_NORMAL) {
3290 connection->status = Connection::STATUS_BROKEN;
3291
3292 if (notify) {
3293 // Notify other system components.
3294 onDispatchCycleBrokenLocked(currentTime, connection);
3295 }
3296 }
3297}
3298
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003299void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3300 while (!queue.empty()) {
3301 DispatchEntry* dispatchEntry = queue.front();
3302 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003303 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 }
3305}
3306
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003307void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
3311 delete dispatchEntry;
3312}
3313
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003314int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3315 std::scoped_lock _l(mLock);
3316 sp<Connection> connection = getConnectionLocked(connectionToken);
3317 if (connection == nullptr) {
3318 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3319 connectionToken.get(), events);
3320 return 0; // remove the callback
3321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003323 bool notify;
3324 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3325 if (!(events & ALOOPER_EVENT_INPUT)) {
3326 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3327 "events=0x%x",
3328 connection->getInputChannelName().c_str(), events);
3329 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 }
3331
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003332 nsecs_t currentTime = now();
3333 bool gotOne = false;
3334 status_t status = OK;
3335 for (;;) {
3336 Result<InputPublisher::ConsumerResponse> result =
3337 connection->inputPublisher.receiveConsumerResponse();
3338 if (!result.ok()) {
3339 status = result.error().code();
3340 break;
3341 }
3342
3343 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3344 const InputPublisher::Finished& finish =
3345 std::get<InputPublisher::Finished>(*result);
3346 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3347 finish.consumeTime);
3348 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003349 if (shouldReportMetricsForConnection(*connection)) {
3350 const InputPublisher::Timeline& timeline =
3351 std::get<InputPublisher::Timeline>(*result);
3352 mLatencyTracker
3353 .trackGraphicsLatency(timeline.inputEventId,
3354 connection->inputChannel->getConnectionToken(),
3355 std::move(timeline.graphicsTimeline));
3356 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003357 }
3358 gotOne = true;
3359 }
3360 if (gotOne) {
3361 runCommandsLockedInterruptible();
3362 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 return 1;
3364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 }
3366
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003367 notify = status != DEAD_OBJECT || !connection->monitor;
3368 if (notify) {
3369 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3370 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3371 status);
3372 }
3373 } else {
3374 // Monitor channels are never explicitly unregistered.
3375 // We do it automatically when the remote endpoint is closed so don't warn about them.
3376 const bool stillHaveWindowHandle =
3377 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3378 notify = !connection->monitor && stillHaveWindowHandle;
3379 if (notify) {
3380 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3381 connection->getInputChannelName().c_str(), events);
3382 }
3383 }
3384
3385 // Remove the channel.
3386 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3387 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388}
3389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003392 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003393 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
3395}
3396
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003397void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003398 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003399 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3400 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3401}
3402
3403void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3404 const CancelationOptions& options,
3405 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3406 for (const auto& it : monitorsByDisplay) {
3407 const std::vector<Monitor>& monitors = it.second;
3408 for (const Monitor& monitor : monitors) {
3409 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003410 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003411 }
3412}
3413
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003415 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003416 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003417 if (connection == nullptr) {
3418 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003420
3421 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422}
3423
3424void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3425 const sp<Connection>& connection, const CancelationOptions& options) {
3426 if (connection->status == Connection::STATUS_BROKEN) {
3427 return;
3428 }
3429
3430 nsecs_t currentTime = now();
3431
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003432 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003433 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003435 if (cancelationEvents.empty()) {
3436 return;
3437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003439 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3440 "with reality: %s, mode=%d.",
3441 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3442 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003444
3445 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003446 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003447 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3448 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003449 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003450 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003451 target.globalScaleFactor = windowInfo->globalScaleFactor;
3452 }
3453 target.inputChannel = connection->inputChannel;
3454 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3455
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003456 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003457 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003458 switch (cancelationEventEntry->type) {
3459 case EventEntry::Type::KEY: {
3460 logOutboundKeyDetails("cancel - ",
3461 static_cast<const KeyEntry&>(*cancelationEventEntry));
3462 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003464 case EventEntry::Type::MOTION: {
3465 logOutboundMotionDetails("cancel - ",
3466 static_cast<const MotionEntry&>(*cancelationEventEntry));
3467 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003469 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003470 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3471 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003472 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003473 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003474 break;
3475 }
3476 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003477 case EventEntry::Type::DEVICE_RESET:
3478 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003479 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003480 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003481 break;
3482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
3484
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003485 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3486 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003488
3489 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490}
3491
Svet Ganov5d3bc372020-01-26 23:11:07 -08003492void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3493 const sp<Connection>& connection) {
3494 if (connection->status == Connection::STATUS_BROKEN) {
3495 return;
3496 }
3497
3498 nsecs_t currentTime = now();
3499
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003500 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003501 connection->inputState.synthesizePointerDownEvents(currentTime);
3502
3503 if (downEvents.empty()) {
3504 return;
3505 }
3506
3507#if DEBUG_OUTBOUND_EVENT_DETAILS
3508 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3509 connection->getInputChannelName().c_str(), downEvents.size());
3510#endif
3511
3512 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003513 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003514 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3515 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003516 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003517 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003518 target.globalScaleFactor = windowInfo->globalScaleFactor;
3519 }
3520 target.inputChannel = connection->inputChannel;
3521 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003523 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003524 switch (downEventEntry->type) {
3525 case EventEntry::Type::MOTION: {
3526 logOutboundMotionDetails("down - ",
3527 static_cast<const MotionEntry&>(*downEventEntry));
3528 break;
3529 }
3530
3531 case EventEntry::Type::KEY:
3532 case EventEntry::Type::FOCUS:
3533 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003534 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003535 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003536 case EventEntry::Type::SENSOR:
3537 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003538 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003539 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003540 break;
3541 }
3542 }
3543
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003544 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3545 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003546 }
3547
3548 startDispatchCycleLocked(currentTime, connection);
3549}
3550
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003551std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3552 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 ALOG_ASSERT(pointerIds.value != 0);
3554
3555 uint32_t splitPointerIndexMap[MAX_POINTERS];
3556 PointerProperties splitPointerProperties[MAX_POINTERS];
3557 PointerCoords splitPointerCoords[MAX_POINTERS];
3558
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003559 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 uint32_t splitPointerCount = 0;
3561
3562 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003565 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 uint32_t pointerId = uint32_t(pointerProperties.id);
3567 if (pointerIds.hasBit(pointerId)) {
3568 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3569 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3570 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003571 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 splitPointerCount += 1;
3573 }
3574 }
3575
3576 if (splitPointerCount != pointerIds.count()) {
3577 // This is bad. We are missing some of the pointers that we expected to deliver.
3578 // Most likely this indicates that we received an ACTION_MOVE events that has
3579 // different pointer ids than we expected based on the previous ACTION_DOWN
3580 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3581 // in this way.
3582 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003583 "we expected there to be %d pointers. This probably means we received "
3584 "a broken sequence of pointer ids from the input device.",
3585 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003586 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 }
3588
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003589 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3592 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3594 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003595 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 uint32_t pointerId = uint32_t(pointerProperties.id);
3597 if (pointerIds.hasBit(pointerId)) {
3598 if (pointerIds.count() == 1) {
3599 // The first/last pointer went down/up.
3600 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003601 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003602 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3603 ? AMOTION_EVENT_ACTION_CANCEL
3604 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 } else {
3606 // A secondary pointer went down/up.
3607 uint32_t splitPointerIndex = 0;
3608 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3609 splitPointerIndex += 1;
3610 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003611 action = maskedAction |
3612 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 }
3614 } else {
3615 // An unrelated pointer changed.
3616 action = AMOTION_EVENT_ACTION_MOVE;
3617 }
3618 }
3619
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003620 int32_t newId = mIdGenerator.nextId();
3621 if (ATRACE_ENABLED()) {
3622 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3623 ") to MotionEvent(id=0x%" PRIx32 ").",
3624 originalMotionEntry.id, newId);
3625 ATRACE_NAME(message.c_str());
3626 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003627 std::unique_ptr<MotionEntry> splitMotionEntry =
3628 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3629 originalMotionEntry.deviceId, originalMotionEntry.source,
3630 originalMotionEntry.displayId,
3631 originalMotionEntry.policyFlags, action,
3632 originalMotionEntry.actionButton,
3633 originalMotionEntry.flags, originalMotionEntry.metaState,
3634 originalMotionEntry.buttonState,
3635 originalMotionEntry.classification,
3636 originalMotionEntry.edgeFlags,
3637 originalMotionEntry.xPrecision,
3638 originalMotionEntry.yPrecision,
3639 originalMotionEntry.xCursorPosition,
3640 originalMotionEntry.yCursorPosition,
3641 originalMotionEntry.downTime, splitPointerCount,
3642 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003644 if (originalMotionEntry.injectionState) {
3645 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 splitMotionEntry->injectionState->refCount += 1;
3647 }
3648
3649 return splitMotionEntry;
3650}
3651
3652void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3653#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003654 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655#endif
3656
3657 bool needWake;
3658 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003659 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003661 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3662 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3663 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 } // release lock
3665
3666 if (needWake) {
3667 mLooper->wake();
3668 }
3669}
3670
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003671/**
3672 * If one of the meta shortcuts is detected, process them here:
3673 * Meta + Backspace -> generate BACK
3674 * Meta + Enter -> generate HOME
3675 * This will potentially overwrite keyCode and metaState.
3676 */
3677void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003678 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003679 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3680 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3681 if (keyCode == AKEYCODE_DEL) {
3682 newKeyCode = AKEYCODE_BACK;
3683 } else if (keyCode == AKEYCODE_ENTER) {
3684 newKeyCode = AKEYCODE_HOME;
3685 }
3686 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003687 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003688 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003689 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003690 keyCode = newKeyCode;
3691 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3692 }
3693 } else if (action == AKEY_EVENT_ACTION_UP) {
3694 // In order to maintain a consistent stream of up and down events, check to see if the key
3695 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3696 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003697 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003698 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003699 auto replacementIt = mReplacedKeys.find(replacement);
3700 if (replacementIt != mReplacedKeys.end()) {
3701 keyCode = replacementIt->second;
3702 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003703 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3704 }
3705 }
3706}
3707
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3709#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003710 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3711 "policyFlags=0x%x, action=0x%x, "
3712 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3713 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3714 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3715 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716#endif
3717 if (!validateKeyEvent(args->action)) {
3718 return;
3719 }
3720
3721 uint32_t policyFlags = args->policyFlags;
3722 int32_t flags = args->flags;
3723 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003724 // InputDispatcher tracks and generates key repeats on behalf of
3725 // whatever notifies it, so repeatCount should always be set to 0
3726 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3728 policyFlags |= POLICY_FLAG_VIRTUAL;
3729 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 if (policyFlags & POLICY_FLAG_FUNCTION) {
3732 metaState |= AMETA_FUNCTION_ON;
3733 }
3734
3735 policyFlags |= POLICY_FLAG_TRUSTED;
3736
Michael Wright78f24442014-08-06 15:55:28 -07003737 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003738 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003739
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003741 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003742 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3743 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744
Michael Wright2b3c3302018-03-02 17:19:13 +00003745 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003747 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3748 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 bool needWake;
3753 { // acquire lock
3754 mLock.lock();
3755
3756 if (shouldSendKeyToInputFilterLocked(args)) {
3757 mLock.unlock();
3758
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003759 policyFlags |= POLICY_FLAG_FILTERED | POLICY_FLAG_INPUTFILTER_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3761 return; // event was consumed by the filter
3762 }
3763
3764 mLock.lock();
3765 }
3766
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003767 std::unique_ptr<KeyEntry> newEntry =
3768 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3769 args->displayId, policyFlags, args->action, flags,
3770 keyCode, args->scanCode, metaState, repeatCount,
3771 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003773 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 mLock.unlock();
3775 } // release lock
3776
3777 if (needWake) {
3778 mLooper->wake();
3779 }
3780}
3781
3782bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3783 return mInputFilterEnabled;
3784}
3785
3786void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3787#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003788 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3789 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003790 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3791 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003792 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003793 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3794 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3795 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3796 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 for (uint32_t i = 0; i < args->pointerCount; i++) {
3798 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003799 "x=%f, y=%f, pressure=%f, size=%f, "
3800 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3801 "orientation=%f",
3802 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3803 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3804 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3805 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3806 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3807 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3808 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3809 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3810 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3811 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3815 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 return;
3817 }
3818
3819 uint32_t policyFlags = args->policyFlags;
3820 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003821
3822 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003823 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003824 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3825 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
3829 bool needWake;
3830 { // acquire lock
3831 mLock.lock();
3832
3833 if (shouldSendMotionToInputFilterLocked(args)) {
3834 mLock.unlock();
3835
3836 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003837 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003838 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3839 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003840 args->metaState, args->buttonState, args->classification, transform,
3841 args->xPrecision, args->yPrecision, args->xCursorPosition,
chaviw98318de2021-05-19 16:45:23 -05003842 args->yCursorPosition, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
3843 args->downTime, args->eventTime, args->pointerCount,
3844 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845
3846 policyFlags |= POLICY_FLAG_FILTERED;
3847 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3848 return; // event was consumed by the filter
3849 }
3850
3851 mLock.lock();
3852 }
3853
3854 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003855 std::unique_ptr<MotionEntry> newEntry =
3856 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3857 args->source, args->displayId, policyFlags,
3858 args->action, args->actionButton, args->flags,
3859 args->metaState, args->buttonState,
3860 args->classification, args->edgeFlags,
3861 args->xPrecision, args->yPrecision,
3862 args->xCursorPosition, args->yCursorPosition,
3863 args->downTime, args->pointerCount,
3864 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003866 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 mLock.unlock();
3868 } // release lock
3869
3870 if (needWake) {
3871 mLooper->wake();
3872 }
3873}
3874
Chris Yef59a2f42020-10-16 12:55:26 -07003875void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3876#if DEBUG_INBOUND_EVENT_DETAILS
3877 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3878 " sensorType=%s",
3879 args->id, args->eventTime, args->deviceId, args->source,
3880 NamedEnum::string(args->sensorType).c_str());
3881#endif
3882
3883 bool needWake;
3884 { // acquire lock
3885 mLock.lock();
3886
3887 // Just enqueue a new sensor event.
3888 std::unique_ptr<SensorEntry> newEntry =
3889 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3890 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3891 args->sensorType, args->accuracy,
3892 args->accuracyChanged, args->values);
3893
3894 needWake = enqueueInboundEventLocked(std::move(newEntry));
3895 mLock.unlock();
3896 } // release lock
3897
3898 if (needWake) {
3899 mLooper->wake();
3900 }
3901}
3902
Chris Yefb552902021-02-03 17:18:37 -08003903void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3904#if DEBUG_INBOUND_EVENT_DETAILS
3905 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3906 args->deviceId, args->isOn);
3907#endif
3908 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3909}
3910
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003912 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913}
3914
3915void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3916#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003917 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003918 "switchMask=0x%08x",
3919 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920#endif
3921
3922 uint32_t policyFlags = args->policyFlags;
3923 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003924 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925}
3926
3927void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3928#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003929 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3930 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931#endif
3932
3933 bool needWake;
3934 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003935 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003937 std::unique_ptr<DeviceResetEntry> newEntry =
3938 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3939 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 } // release lock
3941
3942 if (needWake) {
3943 mLooper->wake();
3944 }
3945}
3946
Prabir Pradhan7e186182020-11-10 13:56:45 -08003947void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3948#if DEBUG_INBOUND_EVENT_DETAILS
3949 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3950 args->enabled ? "true" : "false");
3951#endif
3952
Prabir Pradhan99987712020-11-10 18:43:05 -08003953 bool needWake;
3954 { // acquire lock
3955 std::scoped_lock _l(mLock);
3956 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3957 args->enabled);
3958 needWake = enqueueInboundEventLocked(std::move(entry));
3959 } // release lock
3960
3961 if (needWake) {
3962 mLooper->wake();
3963 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003964}
3965
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003966InputEventInjectionResult InputDispatcher::injectInputEvent(
3967 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3968 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969#if DEBUG_INBOUND_EVENT_DETAILS
3970 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003971 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3972 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003974 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
3976 policyFlags |= POLICY_FLAG_INJECTED;
3977 if (hasInjectionPermission(injectorPid, injectorUid)) {
3978 policyFlags |= POLICY_FLAG_TRUSTED;
3979 }
3980
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003981 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
3982 // that have gone through the InputFilter. If the event passed through the InputFilter,
3983 // but did not get modified, assign the provided device id. If the InputFilter modifies the
3984 // events in any way, it is responsible for removing this flag.
3985 // If the injected event originated from accessibility, assign the accessibility device id,
3986 // so that it can be distinguished from regular injected events.
3987 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
3988 if (policyFlags & POLICY_FLAG_INPUTFILTER_TRUSTED) {
3989 resolvedDeviceId = event->getDeviceId();
3990 } else if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
3991 resolvedDeviceId = ACCESSIBILITY_DEVICE_ID;
3992 }
3993
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003994 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003996 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003997 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3998 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003999 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004000 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004003 int32_t flags = incomingKey.getFlags();
4004 int32_t keyCode = incomingKey.getKeyCode();
4005 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004006 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004007 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004008 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004009 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004010 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4011 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4012 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004014 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4015 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004016 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004017
4018 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4019 android::base::Timer t;
4020 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4021 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4022 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4023 std::to_string(t.duration().count()).c_str());
4024 }
4025 }
4026
4027 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004028 std::unique_ptr<KeyEntry> injectedEntry =
4029 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004030 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004031 incomingKey.getDisplayId(), policyFlags, action,
4032 flags, keyCode, incomingKey.getScanCode(), metaState,
4033 incomingKey.getRepeatCount(),
4034 incomingKey.getDownTime());
4035 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004036 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 }
4038
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004039 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004040 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4041 int32_t action = motionEvent.getAction();
4042 size_t pointerCount = motionEvent.getPointerCount();
4043 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4044 int32_t actionButton = motionEvent.getActionButton();
4045 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004046 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004047 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 }
4049
4050 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004051 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 android::base::Timer t;
4053 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4054 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4055 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4056 std::to_string(t.duration().count()).c_str());
4057 }
4058 }
4059
4060 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004061 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4062 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004063 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004064 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4065 resolvedDeviceId, motionEvent.getSource(),
4066 motionEvent.getDisplayId(), policyFlags, action,
4067 actionButton, motionEvent.getFlags(),
4068 motionEvent.getMetaState(),
4069 motionEvent.getButtonState(),
4070 motionEvent.getClassification(),
4071 motionEvent.getEdgeFlags(),
4072 motionEvent.getXPrecision(),
4073 motionEvent.getYPrecision(),
4074 motionEvent.getRawXCursorPosition(),
4075 motionEvent.getRawYCursorPosition(),
4076 motionEvent.getDownTime(), uint32_t(pointerCount),
4077 pointerProperties, samplePointerCoords,
4078 motionEvent.getXOffset(),
4079 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004080 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004081 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004082 sampleEventTimes += 1;
4083 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004084 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004085 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4086 resolvedDeviceId, motionEvent.getSource(),
4087 motionEvent.getDisplayId(), policyFlags,
4088 action, actionButton, motionEvent.getFlags(),
4089 motionEvent.getMetaState(),
4090 motionEvent.getButtonState(),
4091 motionEvent.getClassification(),
4092 motionEvent.getEdgeFlags(),
4093 motionEvent.getXPrecision(),
4094 motionEvent.getYPrecision(),
4095 motionEvent.getRawXCursorPosition(),
4096 motionEvent.getRawYCursorPosition(),
4097 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004098 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004099 samplePointerCoords, motionEvent.getXOffset(),
4100 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004101 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 }
4103 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004107 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004108 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 }
4110
4111 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004112 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 injectionState->injectionIsAsync = true;
4114 }
4115
4116 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004117 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118
4119 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004120 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004121 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004122 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 }
4124
4125 mLock.unlock();
4126
4127 if (needWake) {
4128 mLooper->wake();
4129 }
4130
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004131 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004133 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004135 if (syncMode == InputEventInjectionSync::NONE) {
4136 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 } else {
4138 for (;;) {
4139 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004140 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 break;
4142 }
4143
4144 nsecs_t remainingTimeout = endTime - now();
4145 if (remainingTimeout <= 0) {
4146#if DEBUG_INJECTION
4147 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004150 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 break;
4152 }
4153
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004154 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 }
4156
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004157 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4158 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 while (injectionState->pendingForegroundDispatches != 0) {
4160#if DEBUG_INJECTION
4161 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163#endif
4164 nsecs_t remainingTimeout = endTime - now();
4165 if (remainingTimeout <= 0) {
4166#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4168 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004170 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 break;
4172 }
4173
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004174 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
4176 }
4177 }
4178
4179 injectionState->release();
4180 } // release lock
4181
4182#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004183 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185#endif
4186
4187 return injectionResult;
4188}
4189
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004190std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004191 std::array<uint8_t, 32> calculatedHmac;
4192 std::unique_ptr<VerifiedInputEvent> result;
4193 switch (event.getType()) {
4194 case AINPUT_EVENT_TYPE_KEY: {
4195 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4196 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4197 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004198 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004199 break;
4200 }
4201 case AINPUT_EVENT_TYPE_MOTION: {
4202 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4203 VerifiedMotionEvent verifiedMotionEvent =
4204 verifiedMotionEventFromMotionEvent(motionEvent);
4205 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004206 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004207 break;
4208 }
4209 default: {
4210 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4211 return nullptr;
4212 }
4213 }
4214 if (calculatedHmac == INVALID_HMAC) {
4215 return nullptr;
4216 }
4217 if (calculatedHmac != event.getHmac()) {
4218 return nullptr;
4219 }
4220 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004221}
4222
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 return injectorUid == 0 ||
4225 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226}
4227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004228void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004229 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004230 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 if (injectionState) {
4232#if DEBUG_INJECTION
4233 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004234 "injectorPid=%d, injectorUid=%d",
4235 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236#endif
4237
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 // Log the outcome since the injector did not wait for the injection result.
4240 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004241 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 ALOGV("Asynchronous input event injection succeeded.");
4243 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004244 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 ALOGW("Asynchronous input event injection failed.");
4246 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004247 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 ALOGW("Asynchronous input event injection permission denied.");
4249 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004250 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 ALOGW("Asynchronous input event injection timed out.");
4252 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004253 case InputEventInjectionResult::PENDING:
4254 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4255 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 }
4257 }
4258
4259 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004260 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 }
4262}
4263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004264void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4265 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 if (injectionState) {
4267 injectionState->pendingForegroundDispatches += 1;
4268 }
4269}
4270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4272 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 if (injectionState) {
4274 injectionState->pendingForegroundDispatches -= 1;
4275
4276 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004277 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279 }
4280}
4281
chaviw98318de2021-05-19 16:45:23 -05004282const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004283 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004284 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004285 auto it = mWindowHandlesByDisplay.find(displayId);
4286 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004287}
4288
chaviw98318de2021-05-19 16:45:23 -05004289sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004290 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004291 if (windowHandleToken == nullptr) {
4292 return nullptr;
4293 }
4294
Arthur Hungb92218b2018-08-14 12:00:21 +08004295 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004296 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4297 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004298 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004299 return windowHandle;
4300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 }
4302 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004303 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304}
4305
chaviw98318de2021-05-19 16:45:23 -05004306sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4307 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004308 if (windowHandleToken == nullptr) {
4309 return nullptr;
4310 }
4311
chaviw98318de2021-05-19 16:45:23 -05004312 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004313 if (windowHandle->getToken() == windowHandleToken) {
4314 return windowHandle;
4315 }
4316 }
4317 return nullptr;
4318}
4319
chaviw98318de2021-05-19 16:45:23 -05004320sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4321 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004322 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004323 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4324 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004325 if (handle->getId() == windowHandle->getId() &&
4326 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004327 if (windowHandle->getInfo()->displayId != it.first) {
4328 ALOGE("Found window %s in display %" PRId32
4329 ", but it should belong to display %" PRId32,
4330 windowHandle->getName().c_str(), it.first,
4331 windowHandle->getInfo()->displayId);
4332 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004333 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 }
4336 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004337 return nullptr;
4338}
4339
chaviw98318de2021-05-19 16:45:23 -05004340sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004341 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4342 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343}
4344
chaviw98318de2021-05-19 16:45:23 -05004345bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004346 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4347 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004348 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004349 if (connection != nullptr && noInputChannel) {
4350 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4351 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4352 return false;
4353 }
4354
4355 if (connection == nullptr) {
4356 if (!noInputChannel) {
4357 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4358 }
4359 return false;
4360 }
4361 if (!connection->responsive) {
4362 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4363 return false;
4364 }
4365 return true;
4366}
4367
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004368std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4369 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004370 auto connectionIt = mConnectionsByToken.find(token);
4371 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004372 return nullptr;
4373 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004374 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004375}
4376
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004377void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004378 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4379 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004380 // Remove all handles on a display if there are no windows left.
4381 mWindowHandlesByDisplay.erase(displayId);
4382 return;
4383 }
4384
4385 // Since we compare the pointer of input window handles across window updates, we need
4386 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004387 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4388 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4389 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004390 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004391 }
4392
chaviw98318de2021-05-19 16:45:23 -05004393 std::vector<sp<WindowInfoHandle>> newHandles;
4394 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004395 if (!handle->updateInfo()) {
4396 // handle no longer valid
4397 continue;
4398 }
4399
chaviw98318de2021-05-19 16:45:23 -05004400 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004401 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004402 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004403 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4404 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4405 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004406 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004407 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004408 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004409 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004410 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004411 }
4412
4413 if (info->displayId != displayId) {
4414 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4415 handle->getName().c_str(), displayId, info->displayId);
4416 continue;
4417 }
4418
Robert Carredd13602020-04-13 17:24:34 -07004419 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4420 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004421 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004422 oldHandle->updateFrom(handle);
4423 newHandles.push_back(oldHandle);
4424 } else {
4425 newHandles.push_back(handle);
4426 }
4427 }
4428
4429 // Insert or replace
4430 mWindowHandlesByDisplay[displayId] = newHandles;
4431}
4432
Arthur Hung72d8dc32020-03-28 00:48:39 +00004433void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004434 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004435 { // acquire lock
4436 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004437 for (const auto& [displayId, handles] : handlesPerDisplay) {
4438 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004439 }
4440 }
4441 // Wake up poll loop since it may need to make new input dispatching choices.
4442 mLooper->wake();
4443}
4444
Arthur Hungb92218b2018-08-14 12:00:21 +08004445/**
4446 * Called from InputManagerService, update window handle list by displayId that can receive input.
4447 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4448 * If set an empty list, remove all handles from the specific display.
4449 * For focused handle, check if need to change and send a cancel event to previous one.
4450 * For removed handle, check if need to send a cancel event if already in touch.
4451 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004452void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004453 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004454 if (DEBUG_FOCUS) {
4455 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004456 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004457 windowList += iwh->getName() + " ";
4458 }
4459 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004462 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004463 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004464 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004465 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004466 if (noInputWindow && window->getToken() != nullptr) {
4467 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4468 window->getName().c_str());
4469 window->releaseChannel();
4470 }
4471 }
4472
Arthur Hung72d8dc32020-03-28 00:48:39 +00004473 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004474 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004476 // Save the old windows' orientation by ID before it gets updated.
4477 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004478 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004479 oldWindowOrientations.emplace(handle->getId(),
4480 handle->getInfo()->transform.getOrientation());
4481 }
4482
chaviw98318de2021-05-19 16:45:23 -05004483 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004484
chaviw98318de2021-05-19 16:45:23 -05004485 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004486 if (mLastHoverWindowHandle &&
4487 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4488 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004489 mLastHoverWindowHandle = nullptr;
4490 }
4491
Vishnu Nairc519ff72021-01-21 08:23:08 -08004492 std::optional<FocusResolver::FocusChanges> changes =
4493 mFocusResolver.setInputWindows(displayId, windowHandles);
4494 if (changes) {
4495 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004498 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4499 mTouchStatesByDisplay.find(displayId);
4500 if (stateIt != mTouchStatesByDisplay.end()) {
4501 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004502 for (size_t i = 0; i < state.windows.size();) {
4503 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004504 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004505 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004506 ALOGD("Touched window was removed: %s in display %" PRId32,
4507 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004508 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004509 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004510 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4511 if (touchedInputChannel != nullptr) {
4512 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4513 "touched window was removed");
4514 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004516 state.windows.erase(state.windows.begin() + i);
4517 } else {
4518 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 }
4520 }
arthurhungb89ccb02020-12-30 16:19:01 +08004521
arthurhung6d4bed92021-03-17 11:59:33 +08004522 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004523 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004524 if (mDragState &&
4525 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004526 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004527 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004528 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004529 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004530
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004531 if (isPerWindowInputRotationEnabled()) {
4532 // Determine if the orientation of any of the input windows have changed, and cancel all
4533 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004534 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4535 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004536 if (newWindowHandle != nullptr &&
4537 newWindowHandle->getInfo()->transform.getOrientation() !=
4538 oldWindowOrientations[oldWindowHandle->getId()]) {
4539 std::shared_ptr<InputChannel> inputChannel =
4540 getInputChannelLocked(newWindowHandle->getToken());
4541 if (inputChannel != nullptr) {
4542 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4543 "touched window's orientation changed");
4544 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4545 }
4546 }
4547 }
4548 }
4549
Arthur Hung72d8dc32020-03-28 00:48:39 +00004550 // Release information for windows that are no longer present.
4551 // This ensures that unused input channels are released promptly.
4552 // Otherwise, they might stick around until the window handle is destroyed
4553 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004554 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004555 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004556 if (DEBUG_FOCUS) {
4557 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004558 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004559 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004560 // To avoid making too many calls into the compat framework, only
4561 // check for window flags when windows are going away.
4562 // TODO(b/157929241) : delete this. This is only needed temporarily
4563 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004564 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004565 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4566 oldWindowHandle->getName().c_str());
4567 if (mCompatService != nullptr) {
4568 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4569 oldWindowHandle->getInfo()->ownerUid);
4570 }
4571 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004572 }
chaviw291d88a2019-02-14 10:33:58 -08004573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574}
4575
4576void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004577 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004578 if (DEBUG_FOCUS) {
4579 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4580 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4581 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004582 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004583 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004584 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 } // release lock
4586
4587 // Wake up poll loop since it may need to make new input dispatching choices.
4588 mLooper->wake();
4589}
4590
Vishnu Nair599f1412021-06-21 10:39:58 -07004591void InputDispatcher::setFocusedApplicationLocked(
4592 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4593 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4594 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4595
4596 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4597 return; // This application is already focused. No need to wake up or change anything.
4598 }
4599
4600 // Set the new application handle.
4601 if (inputApplicationHandle != nullptr) {
4602 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4603 } else {
4604 mFocusedApplicationHandlesByDisplay.erase(displayId);
4605 }
4606
4607 // No matter what the old focused application was, stop waiting on it because it is
4608 // no longer focused.
4609 resetNoFocusedWindowTimeoutLocked();
4610}
4611
Tiger Huang721e26f2018-07-24 22:26:19 +08004612/**
4613 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4614 * the display not specified.
4615 *
4616 * We track any unreleased events for each window. If a window loses the ability to receive the
4617 * released event, we will send a cancel event to it. So when the focused display is changed, we
4618 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4619 * display. The display-specified events won't be affected.
4620 */
4621void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004622 if (DEBUG_FOCUS) {
4623 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4624 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004625 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004626 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004627
4628 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004629 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004630 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004631 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004632 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004633 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004634 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004635 CancelationOptions
4636 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4637 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004638 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004639 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4640 }
4641 }
4642 mFocusedDisplayId = displayId;
4643
Chris Ye3c2d6f52020-08-09 10:39:48 -07004644 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004645 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004646 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004647
Vishnu Nairad321cd2020-08-20 16:40:21 -07004648 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004649 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004650 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004651 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004652 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004653 }
4654 }
4655 }
4656
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004657 if (DEBUG_FOCUS) {
4658 logDispatchStateLocked();
4659 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004660 } // release lock
4661
4662 // Wake up poll loop since it may need to make new input dispatching choices.
4663 mLooper->wake();
4664}
4665
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004667 if (DEBUG_FOCUS) {
4668 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670
4671 bool changed;
4672 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004673 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674
4675 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4676 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004677 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678 }
4679
4680 if (mDispatchEnabled && !enabled) {
4681 resetAndDropEverythingLocked("dispatcher is being disabled");
4682 }
4683
4684 mDispatchEnabled = enabled;
4685 mDispatchFrozen = frozen;
4686 changed = true;
4687 } else {
4688 changed = false;
4689 }
4690
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004691 if (DEBUG_FOCUS) {
4692 logDispatchStateLocked();
4693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 } // release lock
4695
4696 if (changed) {
4697 // Wake up poll loop since it may need to make new input dispatching choices.
4698 mLooper->wake();
4699 }
4700}
4701
4702void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004703 if (DEBUG_FOCUS) {
4704 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706
4707 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004708 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709
4710 if (mInputFilterEnabled == enabled) {
4711 return;
4712 }
4713
4714 mInputFilterEnabled = enabled;
4715 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4716 } // release lock
4717
4718 // Wake up poll loop since there might be work to do to drop everything.
4719 mLooper->wake();
4720}
4721
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004722void InputDispatcher::setInTouchMode(bool inTouchMode) {
4723 std::scoped_lock lock(mLock);
4724 mInTouchMode = inTouchMode;
4725}
4726
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004727void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4728 if (opacity < 0 || opacity > 1) {
4729 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4730 return;
4731 }
4732
4733 std::scoped_lock lock(mLock);
4734 mMaximumObscuringOpacityForTouch = opacity;
4735}
4736
4737void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4738 std::scoped_lock lock(mLock);
4739 mBlockUntrustedTouchesMode = mode;
4740}
4741
arthurhungb89ccb02020-12-30 16:19:01 +08004742bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4743 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004744 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004745 if (DEBUG_FOCUS) {
4746 ALOGD("Trivial transfer to same window.");
4747 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004748 return true;
4749 }
4750
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004752 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
chaviw98318de2021-05-19 16:45:23 -05004754 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4755 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004756 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004757 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 return false;
4759 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004760 if (DEBUG_FOCUS) {
4761 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4762 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004765 if (DEBUG_FOCUS) {
4766 ALOGD("Cannot transfer focus because windows are on different displays.");
4767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 return false;
4769 }
4770
4771 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004772 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4773 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004774 for (size_t i = 0; i < state.windows.size(); i++) {
4775 const TouchedWindow& touchedWindow = state.windows[i];
4776 if (touchedWindow.windowHandle == fromWindowHandle) {
4777 int32_t oldTargetFlags = touchedWindow.targetFlags;
4778 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004780 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004782 int32_t newTargetFlags = oldTargetFlags &
4783 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4784 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004785 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786
arthurhungb89ccb02020-12-30 16:19:01 +08004787 // Store the dragging window.
4788 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004789 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004790 }
4791
Jeff Brownf086ddb2014-02-11 14:28:48 -08004792 found = true;
4793 goto Found;
4794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 }
4796 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004800 if (DEBUG_FOCUS) {
4801 ALOGD("Focus transfer failed because from window did not have focus.");
4802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 return false;
4804 }
4805
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004806 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4807 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004808 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004809 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004810 CancelationOptions
4811 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4812 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004814 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 }
4816
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004817 if (DEBUG_FOCUS) {
4818 logDispatchStateLocked();
4819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 } // release lock
4821
4822 // Wake up poll loop since it may need to make new input dispatching choices.
4823 mLooper->wake();
4824 return true;
4825}
4826
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004827// Binder call
4828bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4829 sp<IBinder> fromToken;
4830 { // acquire lock
4831 std::scoped_lock _l(mLock);
4832
chaviw98318de2021-05-19 16:45:23 -05004833 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004834 if (toWindowHandle == nullptr) {
4835 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4836 return false;
4837 }
4838
4839 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4840
4841 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4842 if (touchStateIt == mTouchStatesByDisplay.end()) {
4843 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4844 displayId);
4845 return false;
4846 }
4847
4848 TouchState& state = touchStateIt->second;
4849 if (state.windows.size() != 1) {
4850 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4851 state.windows.size());
4852 return false;
4853 }
4854 const TouchedWindow& touchedWindow = state.windows[0];
4855 fromToken = touchedWindow.windowHandle->getToken();
4856 } // release lock
4857
4858 return transferTouchFocus(fromToken, destChannelToken);
4859}
4860
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004862 if (DEBUG_FOCUS) {
4863 ALOGD("Resetting and dropping all events (%s).", reason);
4864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865
4866 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4867 synthesizeCancelationEventsForAllConnectionsLocked(options);
4868
4869 resetKeyRepeatLocked();
4870 releasePendingEventLocked();
4871 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004874 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004875 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004877 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878}
4879
4880void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004881 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 dumpDispatchStateLocked(dump);
4883
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004884 std::istringstream stream(dump);
4885 std::string line;
4886
4887 while (std::getline(stream, line, '\n')) {
4888 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 }
4890}
4891
Prabir Pradhan99987712020-11-10 18:43:05 -08004892std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4893 std::string dump;
4894
4895 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4896 toString(mFocusedWindowRequestedPointerCapture));
4897
4898 std::string windowName = "None";
4899 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05004900 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004901 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4902 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4903 : "token has capture without window";
4904 }
4905 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4906
4907 return dump;
4908}
4909
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004910void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004911 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4912 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4913 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004914 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
Tiger Huang721e26f2018-07-24 22:26:19 +08004916 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4917 dump += StringPrintf(INDENT "FocusedApplications:\n");
4918 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4919 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004920 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004921 const std::chrono::duration timeout =
4922 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004923 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004924 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004925 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004928 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004930
Vishnu Nairc519ff72021-01-21 08:23:08 -08004931 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004932 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004934 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004935 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004936 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4937 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004938 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004939 state.displayId, toString(state.down), toString(state.split),
4940 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004941 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004942 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004943 for (size_t i = 0; i < state.windows.size(); i++) {
4944 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 dump += StringPrintf(INDENT4
4946 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4947 i, touchedWindow.windowHandle->getName().c_str(),
4948 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004949 }
4950 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004951 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 }
4954 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004955 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 }
4957
arthurhung6d4bed92021-03-17 11:59:33 +08004958 if (mDragState) {
4959 dump += StringPrintf(INDENT "DragState:\n");
4960 mDragState->dump(dump, INDENT2);
4961 }
4962
Arthur Hungb92218b2018-08-14 12:00:21 +08004963 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004964 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004965 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004966 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004967 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004968 dump += INDENT2 "Windows:\n";
4969 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05004970 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
4971 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004973 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004974 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004975 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004976 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004977 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004978 "applicationInfo.name=%s, "
4979 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004980 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004981 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004982 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004983 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004985 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004986 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004987 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004988 windowInfo->frameLeft, windowInfo->frameTop,
4989 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004990 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004991 windowInfo->applicationInfo.name.c_str(),
4992 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004993 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004994 dump += StringPrintf(", inputFeatures=%s",
4995 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004996 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004997 "ms, trustedOverlay=%s, hasToken=%s, "
4998 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004999 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005000 millis(windowInfo->dispatchingTimeout),
5001 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005002 toString(windowInfo->token != nullptr),
5003 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005004 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005005 }
5006 } else {
5007 dump += INDENT2 "Windows: <none>\n";
5008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 }
5010 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005011 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005012 }
5013
Michael Wright3dd60e22019-03-27 22:06:44 +00005014 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005015 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005016 const std::vector<Monitor>& monitors = it.second;
5017 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5018 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 }
5020 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005021 const std::vector<Monitor>& monitors = it.second;
5022 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5023 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005026 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 }
5028
5029 nsecs_t currentTime = now();
5030
5031 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005032 if (!mRecentQueue.empty()) {
5033 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005034 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005035 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005036 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005037 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
5039 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005040 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 }
5042
5043 // Dump event currently being dispatched.
5044 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005045 dump += INDENT "PendingEvent:\n";
5046 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005047 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005048 dump += StringPrintf(", age=%" PRId64 "ms\n",
5049 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005051 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 }
5053
5054 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005055 if (!mInboundQueue.empty()) {
5056 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005057 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005058 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005059 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005060 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
5062 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005063 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 }
5065
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005066 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005067 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005068 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5069 const KeyReplacement& replacement = pair.first;
5070 int32_t newKeyCode = pair.second;
5071 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005072 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005073 }
5074 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005075 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005076 }
5077
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005078 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005079 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005080 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005081 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005082 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005083 connection->inputChannel->getFd().get(),
5084 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005085 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005086 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005088 if (!connection->outboundQueue.empty()) {
5089 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5090 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005091 dump += dumpQueue(connection->outboundQueue, currentTime);
5092
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005094 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 }
5096
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005097 if (!connection->waitQueue.empty()) {
5098 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5099 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005100 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005102 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 }
5104 }
5105 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 }
5108
5109 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005110 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5111 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005113 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 }
5115
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005116 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005117 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5118 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5119 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005120 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005121 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122}
5123
Michael Wright3dd60e22019-03-27 22:06:44 +00005124void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5125 const size_t numMonitors = monitors.size();
5126 for (size_t i = 0; i < numMonitors; i++) {
5127 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005128 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005129 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5130 dump += "\n";
5131 }
5132}
5133
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005134class LooperEventCallback : public LooperCallback {
5135public:
5136 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5137 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5138
5139private:
5140 std::function<int(int events)> mCallback;
5141};
5142
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005143Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005144#if DEBUG_CHANNEL_CREATION
5145 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146#endif
5147
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005148 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005149 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005150 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005151
5152 if (result) {
5153 return base::Error(result) << "Failed to open input channel pair with name " << name;
5154 }
5155
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005157 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005158 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005159 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005160 sp<Connection> connection =
5161 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005163 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5164 ALOGE("Created a new connection, but the token %p is already known", token.get());
5165 }
5166 mConnectionsByToken.emplace(token, connection);
5167
5168 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5169 this, std::placeholders::_1, token);
5170
5171 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 } // release lock
5173
5174 // Wake the looper because some connections have changed.
5175 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005176 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177}
5178
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005179Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5180 bool isGestureMonitor,
5181 const std::string& name,
5182 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005183 std::shared_ptr<InputChannel> serverChannel;
5184 std::unique_ptr<InputChannel> clientChannel;
5185 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5186 if (result) {
5187 return base::Error(result) << "Failed to open input channel pair with name " << name;
5188 }
5189
Michael Wright3dd60e22019-03-27 22:06:44 +00005190 { // acquire lock
5191 std::scoped_lock _l(mLock);
5192
5193 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005194 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5195 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005196 }
5197
Garfield Tan15601662020-09-22 15:32:38 -07005198 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005199 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005200 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005201
5202 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5203 ALOGE("Created a new connection, but the token %p is already known", token.get());
5204 }
5205 mConnectionsByToken.emplace(token, connection);
5206 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5207 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005208
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005209 auto& monitorsByDisplay =
5210 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005211 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005212
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005213 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005214 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5215 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005216 }
Garfield Tan15601662020-09-22 15:32:38 -07005217
Michael Wright3dd60e22019-03-27 22:06:44 +00005218 // Wake the looper because some connections have changed.
5219 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005220 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005221}
5222
Garfield Tan15601662020-09-22 15:32:38 -07005223status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005225 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226
Garfield Tan15601662020-09-22 15:32:38 -07005227 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228 if (status) {
5229 return status;
5230 }
5231 } // release lock
5232
5233 // Wake the poll loop because removing the connection may have changed the current
5234 // synchronization state.
5235 mLooper->wake();
5236 return OK;
5237}
5238
Garfield Tan15601662020-09-22 15:32:38 -07005239status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5240 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005241 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005242 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005243 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 return BAD_VALUE;
5245 }
5246
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005247 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005248
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005250 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251 }
5252
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005253 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254
5255 nsecs_t currentTime = now();
5256 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5257
5258 connection->status = Connection::STATUS_ZOMBIE;
5259 return OK;
5260}
5261
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005262void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5263 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5264 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005265}
5266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005267void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005268 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005269 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005270 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005271 std::vector<Monitor>& monitors = it->second;
5272 const size_t numMonitors = monitors.size();
5273 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005274 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005275 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5276 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005277 monitors.erase(monitors.begin() + i);
5278 break;
5279 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005280 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005281 if (monitors.empty()) {
5282 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005283 } else {
5284 ++it;
5285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 }
5287}
5288
Michael Wright3dd60e22019-03-27 22:06:44 +00005289status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5290 { // acquire lock
5291 std::scoped_lock _l(mLock);
5292 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5293
5294 if (!foundDisplayId) {
5295 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5296 return BAD_VALUE;
5297 }
5298 int32_t displayId = foundDisplayId.value();
5299
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005300 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5301 mTouchStatesByDisplay.find(displayId);
5302 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005303 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5304 return BAD_VALUE;
5305 }
5306
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005307 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005308 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005309 std::optional<int32_t> foundDeviceId;
5310 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005311 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005312 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005313 foundDeviceId = state.deviceId;
5314 }
5315 }
5316 if (!foundDeviceId || !state.down) {
5317 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005318 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005319 return BAD_VALUE;
5320 }
5321 int32_t deviceId = foundDeviceId.value();
5322
5323 // Send cancel events to all the input channels we're stealing from.
5324 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005325 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005326 options.deviceId = deviceId;
5327 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005328 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005329 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005330 std::shared_ptr<InputChannel> channel =
5331 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005332 if (channel != nullptr) {
5333 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005334 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005335 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005336 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005337 canceledWindows += "]";
5338 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5339 canceledWindows.c_str());
5340
Michael Wright3dd60e22019-03-27 22:06:44 +00005341 // Then clear the current touch state so we stop dispatching to them as well.
5342 state.filterNonMonitors();
5343 }
5344 return OK;
5345}
5346
Prabir Pradhan99987712020-11-10 18:43:05 -08005347void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5348 { // acquire lock
5349 std::scoped_lock _l(mLock);
5350 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005351 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005352 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5353 windowHandle != nullptr ? windowHandle->getName().c_str()
5354 : "token without window");
5355 }
5356
Vishnu Nairc519ff72021-01-21 08:23:08 -08005357 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005358 if (focusedToken != windowToken) {
5359 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5360 enabled ? "enable" : "disable");
5361 return;
5362 }
5363
5364 if (enabled == mFocusedWindowRequestedPointerCapture) {
5365 ALOGW("Ignoring request to %s Pointer Capture: "
5366 "window has %s requested pointer capture.",
5367 enabled ? "enable" : "disable", enabled ? "already" : "not");
5368 return;
5369 }
5370
5371 mFocusedWindowRequestedPointerCapture = enabled;
5372 setPointerCaptureLocked(enabled);
5373 } // release lock
5374
5375 // Wake the thread to process command entries.
5376 mLooper->wake();
5377}
5378
Michael Wright3dd60e22019-03-27 22:06:44 +00005379std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5380 const sp<IBinder>& token) {
5381 for (const auto& it : mGestureMonitorsByDisplay) {
5382 const std::vector<Monitor>& monitors = it.second;
5383 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005384 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 return it.first;
5386 }
5387 }
5388 }
5389 return std::nullopt;
5390}
5391
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005392std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5393 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5394 if (gesturePid.has_value()) {
5395 return gesturePid;
5396 }
5397 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5398}
5399
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005400sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005401 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005402 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005403 }
5404
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005405 for (const auto& [token, connection] : mConnectionsByToken) {
5406 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005407 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 }
5409 }
Robert Carr4e670e52018-08-15 13:26:12 -07005410
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005411 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412}
5413
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005414std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5415 sp<Connection> connection = getConnectionLocked(connectionToken);
5416 if (connection == nullptr) {
5417 return "<nullptr>";
5418 }
5419 return connection->getInputChannelName();
5420}
5421
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005422void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005423 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005424 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005425}
5426
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005427void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5428 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005429 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005430 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5431 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 commandEntry->connection = connection;
5433 commandEntry->eventTime = currentTime;
5434 commandEntry->seq = seq;
5435 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005436 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005437 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438}
5439
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005440void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5441 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005443 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005445 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5446 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005448 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449}
5450
Vishnu Nairad321cd2020-08-20 16:40:21 -07005451void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5452 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005453 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5454 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005455 commandEntry->oldToken = oldToken;
5456 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005457 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005458}
5459
arthurhungf452d0b2021-01-06 00:19:52 +08005460void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5461 std::unique_ptr<CommandEntry> commandEntry =
5462 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5463 commandEntry->newToken = token;
5464 commandEntry->x = x;
5465 commandEntry->y = y;
5466 postCommandLocked(std::move(commandEntry));
5467}
5468
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005469void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5470 if (connection == nullptr) {
5471 LOG_ALWAYS_FATAL("Caller must check for nullness");
5472 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005473 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5474 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005475 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005476 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005477 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005478 return;
5479 }
5480 /**
5481 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5482 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5483 * has changed. This could cause newer entries to time out before the already dispatched
5484 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5485 * processes the events linearly. So providing information about the oldest entry seems to be
5486 * most useful.
5487 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005488 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005489 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5490 std::string reason =
5491 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005492 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005493 ns2ms(currentWait),
5494 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005495 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005496 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005497
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005498 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5499
5500 // Stop waking up for events on this connection, it is already unresponsive
5501 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005502}
5503
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005504void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5505 std::string reason =
5506 StringPrintf("%s does not have a focused window", application->getName().c_str());
5507 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005508
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005509 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5510 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5511 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005512 postCommandLocked(std::move(commandEntry));
5513}
5514
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005515void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5516 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5517 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5518 commandEntry->obscuringPackage = obscuringPackage;
5519 postCommandLocked(std::move(commandEntry));
5520}
5521
chaviw98318de2021-05-19 16:45:23 -05005522void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005523 const std::string& reason) {
5524 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5525 updateLastAnrStateLocked(windowLabel, reason);
5526}
5527
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005528void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5529 const std::string& reason) {
5530 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005531 updateLastAnrStateLocked(windowLabel, reason);
5532}
5533
5534void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5535 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005537 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538 struct tm tm;
5539 localtime_r(&t, &tm);
5540 char timestr[64];
5541 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005542 mLastAnrState.clear();
5543 mLastAnrState += INDENT "ANR:\n";
5544 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005545 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5546 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005547 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548}
5549
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005550void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 mLock.unlock();
5552
5553 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5554
5555 mLock.lock();
5556}
5557
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005558void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 sp<Connection> connection = commandEntry->connection;
5560
5561 if (connection->status != Connection::STATUS_ZOMBIE) {
5562 mLock.unlock();
5563
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005564 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565
5566 mLock.lock();
5567 }
5568}
5569
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005570void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005571 sp<IBinder> oldToken = commandEntry->oldToken;
5572 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005573 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005574 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005575 mLock.lock();
5576}
5577
arthurhungf452d0b2021-01-06 00:19:52 +08005578void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5579 sp<IBinder> newToken = commandEntry->newToken;
5580 mLock.unlock();
5581 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5582 mLock.lock();
5583}
5584
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005585void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005587
5588 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5589
5590 mLock.lock();
5591}
5592
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005593void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005594 mLock.unlock();
5595
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005596 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597
5598 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005599}
5600
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005601void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005602 mLock.unlock();
5603
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005604 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5605
5606 mLock.lock();
5607}
5608
5609void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5610 mLock.unlock();
5611
5612 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5613
5614 mLock.lock();
5615}
5616
5617void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5618 mLock.unlock();
5619
5620 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005621
5622 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005623}
5624
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005625void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5626 mLock.unlock();
5627
5628 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5629
5630 mLock.lock();
5631}
5632
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5634 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005635 KeyEntry& entry = *(commandEntry->keyEntry);
5636 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637
5638 mLock.unlock();
5639
Michael Wright2b3c3302018-03-02 17:19:13 +00005640 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005641 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005642 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005643 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5644 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005645 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647
5648 mLock.lock();
5649
5650 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005651 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005653 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005655 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5656 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658}
5659
chaviwfd6d3512019-03-25 13:23:49 -07005660void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5661 mLock.unlock();
5662 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5663 mLock.lock();
5664}
5665
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005666/**
5667 * Connection is responsive if it has no events in the waitQueue that are older than the
5668 * current time.
5669 */
5670static bool isConnectionResponsive(const Connection& connection) {
5671 const nsecs_t currentTime = now();
5672 for (const DispatchEntry* entry : connection.waitQueue) {
5673 if (entry->timeoutTime < currentTime) {
5674 return false;
5675 }
5676 }
5677 return true;
5678}
5679
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005680void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005682 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005684 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685
5686 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005687 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005688 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005689 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005691 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005692 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005693 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005694 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5695 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005696 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005697 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5698 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5699 connection->inputChannel->getConnectionToken(),
5700 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5701 finishTime);
5702 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005703
5704 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005705 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005706 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005707 restartEvent =
5708 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005709 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005710 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005711 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5712 handled);
5713 } else {
5714 restartEvent = false;
5715 }
5716
5717 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005718 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005719 // contents of the wait queue to have been drained, so we need to double-check
5720 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005721 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5722 if (dispatchEntryIt != connection->waitQueue.end()) {
5723 dispatchEntry = *dispatchEntryIt;
5724 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005725 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5726 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005727 if (!connection->responsive) {
5728 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005729 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005730 // The connection was unresponsive, and now it's responsive.
5731 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005732 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005733 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005734 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005735 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005736 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005737 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005738 } else {
5739 releaseDispatchEntry(dispatchEntry);
5740 }
5741 }
5742
5743 // Start the next dispatch cycle for this connection.
5744 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745}
5746
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005747void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5748 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5749 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5750 monitorUnresponsiveCommand->pid = pid;
5751 monitorUnresponsiveCommand->reason = std::move(reason);
5752 postCommandLocked(std::move(monitorUnresponsiveCommand));
5753}
5754
5755void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5756 std::string reason) {
5757 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5758 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5759 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5760 windowUnresponsiveCommand->reason = std::move(reason);
5761 postCommandLocked(std::move(windowUnresponsiveCommand));
5762}
5763
5764void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5765 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5766 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5767 monitorResponsiveCommand->pid = pid;
5768 postCommandLocked(std::move(monitorResponsiveCommand));
5769}
5770
5771void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5772 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5773 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5774 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5775 postCommandLocked(std::move(windowResponsiveCommand));
5776}
5777
5778/**
5779 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5780 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5781 * command entry to the command queue.
5782 */
5783void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5784 std::string reason) {
5785 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5786 if (connection.monitor) {
5787 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5788 reason.c_str());
5789 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5790 if (!pid.has_value()) {
5791 ALOGE("Could not find unresponsive monitor for connection %s",
5792 connection.inputChannel->getName().c_str());
5793 return;
5794 }
5795 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5796 return;
5797 }
5798 // If not a monitor, must be a window
5799 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5800 reason.c_str());
5801 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5802}
5803
5804/**
5805 * Tell the policy that a connection has become responsive so that it can stop ANR.
5806 */
5807void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5808 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5809 if (connection.monitor) {
5810 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5811 if (!pid.has_value()) {
5812 ALOGE("Could not find responsive monitor for connection %s",
5813 connection.inputChannel->getName().c_str());
5814 return;
5815 }
5816 sendMonitorResponsiveCommandLocked(pid.value());
5817 return;
5818 }
5819 // If not a monitor, must be a window
5820 sendWindowResponsiveCommandLocked(connectionToken);
5821}
5822
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005824 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005825 KeyEntry& keyEntry, bool handled) {
5826 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005827 if (!handled) {
5828 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005829 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005830 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005831 return false;
5832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005834 // Get the fallback key state.
5835 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005836 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005837 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005838 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005839 connection->inputState.removeFallbackKey(originalKeyCode);
5840 }
5841
5842 if (handled || !dispatchEntry->hasForegroundTarget()) {
5843 // If the application handles the original key for which we previously
5844 // generated a fallback or if the window is not a foreground window,
5845 // then cancel the associated fallback key, if any.
5846 if (fallbackKeyCode != -1) {
5847 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005849 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005850 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005851 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005853 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005854 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855
5856 mLock.unlock();
5857
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005858 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005859 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860
5861 mLock.lock();
5862
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005863 // Cancel the fallback key.
5864 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005866 "application handled the original non-fallback key "
5867 "or is no longer a foreground target, "
5868 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869 options.keyCode = fallbackKeyCode;
5870 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005872 connection->inputState.removeFallbackKey(originalKeyCode);
5873 }
5874 } else {
5875 // If the application did not handle a non-fallback key, first check
5876 // that we are in a good state to perform unhandled key event processing
5877 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005878 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005879 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005882 "since this is not an initial down. "
5883 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005884 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005886 return false;
5887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889 // Dispatch the unhandled key to the policy.
5890#if DEBUG_OUTBOUND_EVENT_DETAILS
5891 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005892 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005893 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005894#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005895 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005896
5897 mLock.unlock();
5898
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005899 bool fallback =
5900 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005901 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005902
5903 mLock.lock();
5904
5905 if (connection->status != Connection::STATUS_NORMAL) {
5906 connection->inputState.removeFallbackKey(originalKeyCode);
5907 return false;
5908 }
5909
5910 // Latch the fallback keycode for this key on an initial down.
5911 // The fallback keycode cannot change at any other point in the lifecycle.
5912 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005914 fallbackKeyCode = event.getKeyCode();
5915 } else {
5916 fallbackKeyCode = AKEYCODE_UNKNOWN;
5917 }
5918 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5919 }
5920
5921 ALOG_ASSERT(fallbackKeyCode != -1);
5922
5923 // Cancel the fallback key if the policy decides not to send it anymore.
5924 // We will continue to dispatch the key to the policy but we will no
5925 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005926 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5927 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005928#if DEBUG_OUTBOUND_EVENT_DETAILS
5929 if (fallback) {
5930 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005931 "as a fallback for %d, but on the DOWN it had requested "
5932 "to send %d instead. Fallback canceled.",
5933 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005934 } else {
5935 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005936 "but on the DOWN it had requested to send %d. "
5937 "Fallback canceled.",
5938 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005939 }
5940#endif
5941
5942 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5943 "canceling fallback, policy no longer desires it");
5944 options.keyCode = fallbackKeyCode;
5945 synthesizeCancelationEventsForConnectionLocked(connection, options);
5946
5947 fallback = false;
5948 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005949 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005950 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005951 }
5952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953
5954#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955 {
5956 std::string msg;
5957 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5958 connection->inputState.getFallbackKeys();
5959 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005960 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005962 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005963 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005964 }
5965#endif
5966
5967 if (fallback) {
5968 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005969 keyEntry.eventTime = event.getEventTime();
5970 keyEntry.deviceId = event.getDeviceId();
5971 keyEntry.source = event.getSource();
5972 keyEntry.displayId = event.getDisplayId();
5973 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5974 keyEntry.keyCode = fallbackKeyCode;
5975 keyEntry.scanCode = event.getScanCode();
5976 keyEntry.metaState = event.getMetaState();
5977 keyEntry.repeatCount = event.getRepeatCount();
5978 keyEntry.downTime = event.getDownTime();
5979 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005980
5981#if DEBUG_OUTBOUND_EVENT_DETAILS
5982 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005983 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005984 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985#endif
5986 return true; // restart the event
5987 } else {
5988#if DEBUG_OUTBOUND_EVENT_DETAILS
5989 ALOGD("Unhandled key event: No fallback key.");
5990#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005991
5992 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005993 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005994 }
5995 }
5996 return false;
5997}
5998
5999bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006000 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006001 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002 return false;
6003}
6004
6005void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6006 mLock.unlock();
6007
Sean Stoutb4e0a592021-02-23 07:34:53 -08006008 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6009 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010
6011 mLock.lock();
6012}
6013
Michael Wrightd02c5b62014-02-10 15:10:22 -08006014void InputDispatcher::traceInboundQueueLengthLocked() {
6015 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006016 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017 }
6018}
6019
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006020void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006021 if (ATRACE_ENABLED()) {
6022 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006023 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6024 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006025 }
6026}
6027
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006028void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 if (ATRACE_ENABLED()) {
6030 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006031 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6032 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033 }
6034}
6035
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006036void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006037 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006039 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006040 dumpDispatchStateLocked(dump);
6041
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006042 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006043 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006044 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 }
6046}
6047
6048void InputDispatcher::monitor() {
6049 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006050 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006052 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053}
6054
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006055/**
6056 * Wake up the dispatcher and wait until it processes all events and commands.
6057 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6058 * this method can be safely called from any thread, as long as you've ensured that
6059 * the work you are interested in completing has already been queued.
6060 */
6061bool InputDispatcher::waitForIdle() {
6062 /**
6063 * Timeout should represent the longest possible time that a device might spend processing
6064 * events and commands.
6065 */
6066 constexpr std::chrono::duration TIMEOUT = 100ms;
6067 std::unique_lock lock(mLock);
6068 mLooper->wake();
6069 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6070 return result == std::cv_status::no_timeout;
6071}
6072
Vishnu Naire798b472020-07-23 13:52:21 -07006073/**
6074 * Sets focus to the window identified by the token. This must be called
6075 * after updating any input window handles.
6076 *
6077 * Params:
6078 * request.token - input channel token used to identify the window that should gain focus.
6079 * request.focusedToken - the token that the caller expects currently to be focused. If the
6080 * specified token does not match the currently focused window, this request will be dropped.
6081 * If the specified focused token matches the currently focused window, the call will succeed.
6082 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6083 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6084 * when requesting the focus change. This determines which request gets
6085 * precedence if there is a focus change request from another source such as pointer down.
6086 */
Vishnu Nair958da932020-08-21 17:12:37 -07006087void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6088 { // acquire lock
6089 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006090 std::optional<FocusResolver::FocusChanges> changes =
6091 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6092 if (changes) {
6093 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006094 }
6095 } // release lock
6096 // Wake up poll loop since it may need to make new input dispatching choices.
6097 mLooper->wake();
6098}
6099
Vishnu Nairc519ff72021-01-21 08:23:08 -08006100void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6101 if (changes.oldFocus) {
6102 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006103 if (focusedInputChannel) {
6104 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6105 "focus left window");
6106 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006107 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006108 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006109 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006110 if (changes.newFocus) {
6111 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006112 }
6113
Prabir Pradhan99987712020-11-10 18:43:05 -08006114 // If a window has pointer capture, then it must have focus. We need to ensure that this
6115 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6116 // If the window loses focus before it loses pointer capture, then the window can be in a state
6117 // where it has pointer capture but not focus, violating the contract. Therefore we must
6118 // dispatch the pointer capture event before the focus event. Since focus events are added to
6119 // the front of the queue (above), we add the pointer capture event to the front of the queue
6120 // after the focus events are added. This ensures the pointer capture event ends up at the
6121 // front.
6122 disablePointerCaptureForcedLocked();
6123
Vishnu Nairc519ff72021-01-21 08:23:08 -08006124 if (mFocusedDisplayId == changes.displayId) {
6125 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006126 }
6127}
Vishnu Nair958da932020-08-21 17:12:37 -07006128
Prabir Pradhan99987712020-11-10 18:43:05 -08006129void InputDispatcher::disablePointerCaptureForcedLocked() {
6130 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6131 return;
6132 }
6133
6134 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6135
6136 if (mFocusedWindowRequestedPointerCapture) {
6137 mFocusedWindowRequestedPointerCapture = false;
6138 setPointerCaptureLocked(false);
6139 }
6140
6141 if (!mWindowTokenWithPointerCapture) {
6142 // No need to send capture changes because no window has capture.
6143 return;
6144 }
6145
6146 if (mPendingEvent != nullptr) {
6147 // Move the pending event to the front of the queue. This will give the chance
6148 // for the pending event to be dropped if it is a captured event.
6149 mInboundQueue.push_front(mPendingEvent);
6150 mPendingEvent = nullptr;
6151 }
6152
6153 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6154 false /* hasCapture */);
6155 mInboundQueue.push_front(std::move(entry));
6156}
6157
Prabir Pradhan99987712020-11-10 18:43:05 -08006158void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6159 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6160 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6161 commandEntry->enabled = enabled;
6162 postCommandLocked(std::move(commandEntry));
6163}
6164
6165void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6166 android::inputdispatcher::CommandEntry* commandEntry) {
6167 mLock.unlock();
6168
6169 mPolicy->setPointerCapture(commandEntry->enabled);
6170
6171 mLock.lock();
6172}
6173
Vishnu Nair599f1412021-06-21 10:39:58 -07006174void InputDispatcher::displayRemoved(int32_t displayId) {
6175 { // acquire lock
6176 std::scoped_lock _l(mLock);
6177 // Set an empty list to remove all handles from the specific display.
6178 setInputWindowsLocked(/* window handles */ {}, displayId);
6179 setFocusedApplicationLocked(displayId, nullptr);
6180 // Call focus resolver to clean up stale requests. This must be called after input windows
6181 // have been removed for the removed display.
6182 mFocusResolver.displayRemoved(displayId);
6183 } // release lock
6184
6185 // Wake up poll loop since it may need to make new input dispatching choices.
6186 mLooper->wake();
6187}
6188
Garfield Tane84e6f92019-08-29 17:28:41 -07006189} // namespace android::inputdispatcher