blob: d8af48ed4b910ec77425b73b33295ba1ca70dd69 [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 Vishniakouf00a4ec2021-06-16 03:55:32 +00003759 policyFlags |= POLICY_FLAG_FILTERED;
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
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003982 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
3983 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
3984 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
3985 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
3986 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003987 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003988 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003989 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003990 }
3991
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003992 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003994 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003995 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3996 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003997 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003998 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004001 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004002 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4003 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4004 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004005 int32_t keyCode = incomingKey.getKeyCode();
4006 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004007 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004008 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004009 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004010 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004011 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4012 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4013 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4016 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004017 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004018
4019 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4020 android::base::Timer t;
4021 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4022 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4023 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4024 std::to_string(t.duration().count()).c_str());
4025 }
4026 }
4027
4028 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004029 std::unique_ptr<KeyEntry> injectedEntry =
4030 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004031 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004032 incomingKey.getDisplayId(), policyFlags, action,
4033 flags, keyCode, incomingKey.getScanCode(), metaState,
4034 incomingKey.getRepeatCount(),
4035 incomingKey.getDownTime());
4036 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004037 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038 }
4039
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004041 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4042 int32_t action = motionEvent.getAction();
4043 size_t pointerCount = motionEvent.getPointerCount();
4044 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4045 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004046 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004047 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004049 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004050 }
4051
4052 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004053 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 android::base::Timer t;
4055 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4056 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4057 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4058 std::to_string(t.duration().count()).c_str());
4059 }
4060 }
4061
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004062 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4063 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4064 }
4065
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004066 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004067 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4068 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004070 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4071 resolvedDeviceId, motionEvent.getSource(),
4072 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004073 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004074 motionEvent.getButtonState(),
4075 motionEvent.getClassification(),
4076 motionEvent.getEdgeFlags(),
4077 motionEvent.getXPrecision(),
4078 motionEvent.getYPrecision(),
4079 motionEvent.getRawXCursorPosition(),
4080 motionEvent.getRawYCursorPosition(),
4081 motionEvent.getDownTime(), uint32_t(pointerCount),
4082 pointerProperties, samplePointerCoords,
4083 motionEvent.getXOffset(),
4084 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004085 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004086 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 sampleEventTimes += 1;
4088 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004089 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004090 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4091 resolvedDeviceId, motionEvent.getSource(),
4092 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004093 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004094 motionEvent.getMetaState(),
4095 motionEvent.getButtonState(),
4096 motionEvent.getClassification(),
4097 motionEvent.getEdgeFlags(),
4098 motionEvent.getXPrecision(),
4099 motionEvent.getYPrecision(),
4100 motionEvent.getRawXCursorPosition(),
4101 motionEvent.getRawYCursorPosition(),
4102 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004103 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004104 samplePointerCoords, motionEvent.getXOffset(),
4105 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004106 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004107 }
4108 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004111 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004112 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004113 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 }
4115
4116 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004117 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 injectionState->injectionIsAsync = true;
4119 }
4120
4121 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004122 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123
4124 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004125 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004126 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004127 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 }
4129
4130 mLock.unlock();
4131
4132 if (needWake) {
4133 mLooper->wake();
4134 }
4135
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004136 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004138 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004140 if (syncMode == InputEventInjectionSync::NONE) {
4141 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 } else {
4143 for (;;) {
4144 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004145 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 break;
4147 }
4148
4149 nsecs_t remainingTimeout = endTime - now();
4150 if (remainingTimeout <= 0) {
4151#if DEBUG_INJECTION
4152 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004155 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156 break;
4157 }
4158
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004159 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 }
4161
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004162 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4163 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 while (injectionState->pendingForegroundDispatches != 0) {
4165#if DEBUG_INJECTION
4166 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168#endif
4169 nsecs_t remainingTimeout = endTime - now();
4170 if (remainingTimeout <= 0) {
4171#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4173 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004175 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 break;
4177 }
4178
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004179 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181 }
4182 }
4183
4184 injectionState->release();
4185 } // release lock
4186
4187#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004188 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004189 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190#endif
4191
4192 return injectionResult;
4193}
4194
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004195std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004196 std::array<uint8_t, 32> calculatedHmac;
4197 std::unique_ptr<VerifiedInputEvent> result;
4198 switch (event.getType()) {
4199 case AINPUT_EVENT_TYPE_KEY: {
4200 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4201 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4202 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004203 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004204 break;
4205 }
4206 case AINPUT_EVENT_TYPE_MOTION: {
4207 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4208 VerifiedMotionEvent verifiedMotionEvent =
4209 verifiedMotionEventFromMotionEvent(motionEvent);
4210 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004211 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004212 break;
4213 }
4214 default: {
4215 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4216 return nullptr;
4217 }
4218 }
4219 if (calculatedHmac == INVALID_HMAC) {
4220 return nullptr;
4221 }
4222 if (calculatedHmac != event.getHmac()) {
4223 return nullptr;
4224 }
4225 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004226}
4227
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 return injectorUid == 0 ||
4230 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231}
4232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004234 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004235 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 if (injectionState) {
4237#if DEBUG_INJECTION
4238 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 "injectorPid=%d, injectorUid=%d",
4240 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241#endif
4242
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004243 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 // Log the outcome since the injector did not wait for the injection result.
4245 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004246 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 ALOGV("Asynchronous input event injection succeeded.");
4248 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004249 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 ALOGW("Asynchronous input event injection failed.");
4251 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004252 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004253 ALOGW("Asynchronous input event injection permission denied.");
4254 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004255 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004256 ALOGW("Asynchronous input event injection timed out.");
4257 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004258 case InputEventInjectionResult::PENDING:
4259 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4260 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 }
4262 }
4263
4264 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004265 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267}
4268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004269void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4270 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 if (injectionState) {
4272 injectionState->pendingForegroundDispatches += 1;
4273 }
4274}
4275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4277 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 if (injectionState) {
4279 injectionState->pendingForegroundDispatches -= 1;
4280
4281 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004282 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 }
4284 }
4285}
4286
chaviw98318de2021-05-19 16:45:23 -05004287const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004288 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004289 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004290 auto it = mWindowHandlesByDisplay.find(displayId);
4291 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004292}
4293
chaviw98318de2021-05-19 16:45:23 -05004294sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004295 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004296 if (windowHandleToken == nullptr) {
4297 return nullptr;
4298 }
4299
Arthur Hungb92218b2018-08-14 12:00:21 +08004300 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004301 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4302 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004303 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004304 return windowHandle;
4305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 }
4307 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004308 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309}
4310
chaviw98318de2021-05-19 16:45:23 -05004311sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4312 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004313 if (windowHandleToken == nullptr) {
4314 return nullptr;
4315 }
4316
chaviw98318de2021-05-19 16:45:23 -05004317 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004318 if (windowHandle->getToken() == windowHandleToken) {
4319 return windowHandle;
4320 }
4321 }
4322 return nullptr;
4323}
4324
chaviw98318de2021-05-19 16:45:23 -05004325sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4326 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004327 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004328 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4329 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004330 if (handle->getId() == windowHandle->getId() &&
4331 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004332 if (windowHandle->getInfo()->displayId != it.first) {
4333 ALOGE("Found window %s in display %" PRId32
4334 ", but it should belong to display %" PRId32,
4335 windowHandle->getName().c_str(), it.first,
4336 windowHandle->getInfo()->displayId);
4337 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004338 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
4341 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004342 return nullptr;
4343}
4344
chaviw98318de2021-05-19 16:45:23 -05004345sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004346 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4347 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348}
4349
chaviw98318de2021-05-19 16:45:23 -05004350bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004351 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4352 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004353 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004354 if (connection != nullptr && noInputChannel) {
4355 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4356 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4357 return false;
4358 }
4359
4360 if (connection == nullptr) {
4361 if (!noInputChannel) {
4362 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4363 }
4364 return false;
4365 }
4366 if (!connection->responsive) {
4367 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4368 return false;
4369 }
4370 return true;
4371}
4372
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004373std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4374 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004375 auto connectionIt = mConnectionsByToken.find(token);
4376 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004377 return nullptr;
4378 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004379 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004380}
4381
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004382void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004383 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4384 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004385 // Remove all handles on a display if there are no windows left.
4386 mWindowHandlesByDisplay.erase(displayId);
4387 return;
4388 }
4389
4390 // Since we compare the pointer of input window handles across window updates, we need
4391 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004392 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4393 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4394 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004395 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004396 }
4397
chaviw98318de2021-05-19 16:45:23 -05004398 std::vector<sp<WindowInfoHandle>> newHandles;
4399 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004400 if (!handle->updateInfo()) {
4401 // handle no longer valid
4402 continue;
4403 }
4404
chaviw98318de2021-05-19 16:45:23 -05004405 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004406 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004407 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004408 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4409 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4410 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004411 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004412 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004413 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004414 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004415 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004416 }
4417
4418 if (info->displayId != displayId) {
4419 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4420 handle->getName().c_str(), displayId, info->displayId);
4421 continue;
4422 }
4423
Robert Carredd13602020-04-13 17:24:34 -07004424 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4425 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004426 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004427 oldHandle->updateFrom(handle);
4428 newHandles.push_back(oldHandle);
4429 } else {
4430 newHandles.push_back(handle);
4431 }
4432 }
4433
4434 // Insert or replace
4435 mWindowHandlesByDisplay[displayId] = newHandles;
4436}
4437
Arthur Hung72d8dc32020-03-28 00:48:39 +00004438void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004439 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004440 { // acquire lock
4441 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004442 for (const auto& [displayId, handles] : handlesPerDisplay) {
4443 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004444 }
4445 }
4446 // Wake up poll loop since it may need to make new input dispatching choices.
4447 mLooper->wake();
4448}
4449
Arthur Hungb92218b2018-08-14 12:00:21 +08004450/**
4451 * Called from InputManagerService, update window handle list by displayId that can receive input.
4452 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4453 * If set an empty list, remove all handles from the specific display.
4454 * For focused handle, check if need to change and send a cancel event to previous one.
4455 * For removed handle, check if need to send a cancel event if already in touch.
4456 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004457void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004458 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004459 if (DEBUG_FOCUS) {
4460 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004461 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004462 windowList += iwh->getName() + " ";
4463 }
4464 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004467 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004468 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004469 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004470 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004471 if (noInputWindow && window->getToken() != nullptr) {
4472 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4473 window->getName().c_str());
4474 window->releaseChannel();
4475 }
4476 }
4477
Arthur Hung72d8dc32020-03-28 00:48:39 +00004478 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004479 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004481 // Save the old windows' orientation by ID before it gets updated.
4482 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004483 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004484 oldWindowOrientations.emplace(handle->getId(),
4485 handle->getInfo()->transform.getOrientation());
4486 }
4487
chaviw98318de2021-05-19 16:45:23 -05004488 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004489
chaviw98318de2021-05-19 16:45:23 -05004490 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004491 if (mLastHoverWindowHandle &&
4492 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4493 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004494 mLastHoverWindowHandle = nullptr;
4495 }
4496
Vishnu Nairc519ff72021-01-21 08:23:08 -08004497 std::optional<FocusResolver::FocusChanges> changes =
4498 mFocusResolver.setInputWindows(displayId, windowHandles);
4499 if (changes) {
4500 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004503 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4504 mTouchStatesByDisplay.find(displayId);
4505 if (stateIt != mTouchStatesByDisplay.end()) {
4506 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004507 for (size_t i = 0; i < state.windows.size();) {
4508 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004509 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004510 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004511 ALOGD("Touched window was removed: %s in display %" PRId32,
4512 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004513 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004514 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004515 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4516 if (touchedInputChannel != nullptr) {
4517 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4518 "touched window was removed");
4519 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004521 state.windows.erase(state.windows.begin() + i);
4522 } else {
4523 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 }
4525 }
arthurhungb89ccb02020-12-30 16:19:01 +08004526
arthurhung6d4bed92021-03-17 11:59:33 +08004527 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004528 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004529 if (mDragState &&
4530 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004531 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004532 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004533 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004534 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004535
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004536 if (isPerWindowInputRotationEnabled()) {
4537 // Determine if the orientation of any of the input windows have changed, and cancel all
4538 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004539 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4540 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004541 if (newWindowHandle != nullptr &&
4542 newWindowHandle->getInfo()->transform.getOrientation() !=
4543 oldWindowOrientations[oldWindowHandle->getId()]) {
4544 std::shared_ptr<InputChannel> inputChannel =
4545 getInputChannelLocked(newWindowHandle->getToken());
4546 if (inputChannel != nullptr) {
4547 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4548 "touched window's orientation changed");
4549 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4550 }
4551 }
4552 }
4553 }
4554
Arthur Hung72d8dc32020-03-28 00:48:39 +00004555 // Release information for windows that are no longer present.
4556 // This ensures that unused input channels are released promptly.
4557 // Otherwise, they might stick around until the window handle is destroyed
4558 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004559 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004560 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004561 if (DEBUG_FOCUS) {
4562 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004563 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004564 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004565 // To avoid making too many calls into the compat framework, only
4566 // check for window flags when windows are going away.
4567 // TODO(b/157929241) : delete this. This is only needed temporarily
4568 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004569 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004570 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4571 oldWindowHandle->getName().c_str());
4572 if (mCompatService != nullptr) {
4573 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4574 oldWindowHandle->getInfo()->ownerUid);
4575 }
4576 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004577 }
chaviw291d88a2019-02-14 10:33:58 -08004578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579}
4580
4581void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004582 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004583 if (DEBUG_FOCUS) {
4584 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4585 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4586 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004587 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004588 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004589 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 } // release lock
4591
4592 // Wake up poll loop since it may need to make new input dispatching choices.
4593 mLooper->wake();
4594}
4595
Vishnu Nair599f1412021-06-21 10:39:58 -07004596void InputDispatcher::setFocusedApplicationLocked(
4597 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4598 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4599 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4600
4601 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4602 return; // This application is already focused. No need to wake up or change anything.
4603 }
4604
4605 // Set the new application handle.
4606 if (inputApplicationHandle != nullptr) {
4607 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4608 } else {
4609 mFocusedApplicationHandlesByDisplay.erase(displayId);
4610 }
4611
4612 // No matter what the old focused application was, stop waiting on it because it is
4613 // no longer focused.
4614 resetNoFocusedWindowTimeoutLocked();
4615}
4616
Tiger Huang721e26f2018-07-24 22:26:19 +08004617/**
4618 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4619 * the display not specified.
4620 *
4621 * We track any unreleased events for each window. If a window loses the ability to receive the
4622 * released event, we will send a cancel event to it. So when the focused display is changed, we
4623 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4624 * display. The display-specified events won't be affected.
4625 */
4626void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004627 if (DEBUG_FOCUS) {
4628 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4629 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004630 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004631 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004632
4633 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004634 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004635 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004636 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004637 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004638 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004639 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640 CancelationOptions
4641 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4642 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004643 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004644 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4645 }
4646 }
4647 mFocusedDisplayId = displayId;
4648
Chris Ye3c2d6f52020-08-09 10:39:48 -07004649 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004650 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004651 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004652
Vishnu Nairad321cd2020-08-20 16:40:21 -07004653 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004654 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004655 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004656 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004657 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004658 }
4659 }
4660 }
4661
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004662 if (DEBUG_FOCUS) {
4663 logDispatchStateLocked();
4664 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004665 } // release lock
4666
4667 // Wake up poll loop since it may need to make new input dispatching choices.
4668 mLooper->wake();
4669}
4670
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004672 if (DEBUG_FOCUS) {
4673 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675
4676 bool changed;
4677 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004678 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
4680 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4681 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004682 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 }
4684
4685 if (mDispatchEnabled && !enabled) {
4686 resetAndDropEverythingLocked("dispatcher is being disabled");
4687 }
4688
4689 mDispatchEnabled = enabled;
4690 mDispatchFrozen = frozen;
4691 changed = true;
4692 } else {
4693 changed = false;
4694 }
4695
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004696 if (DEBUG_FOCUS) {
4697 logDispatchStateLocked();
4698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 } // release lock
4700
4701 if (changed) {
4702 // Wake up poll loop since it may need to make new input dispatching choices.
4703 mLooper->wake();
4704 }
4705}
4706
4707void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004708 if (DEBUG_FOCUS) {
4709 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711
4712 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004713 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714
4715 if (mInputFilterEnabled == enabled) {
4716 return;
4717 }
4718
4719 mInputFilterEnabled = enabled;
4720 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4721 } // release lock
4722
4723 // Wake up poll loop since there might be work to do to drop everything.
4724 mLooper->wake();
4725}
4726
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004727void InputDispatcher::setInTouchMode(bool inTouchMode) {
4728 std::scoped_lock lock(mLock);
4729 mInTouchMode = inTouchMode;
4730}
4731
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004732void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4733 if (opacity < 0 || opacity > 1) {
4734 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4735 return;
4736 }
4737
4738 std::scoped_lock lock(mLock);
4739 mMaximumObscuringOpacityForTouch = opacity;
4740}
4741
4742void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4743 std::scoped_lock lock(mLock);
4744 mBlockUntrustedTouchesMode = mode;
4745}
4746
arthurhungb89ccb02020-12-30 16:19:01 +08004747bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4748 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004749 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004750 if (DEBUG_FOCUS) {
4751 ALOGD("Trivial transfer to same window.");
4752 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004753 return true;
4754 }
4755
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004757 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
chaviw98318de2021-05-19 16:45:23 -05004759 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4760 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004761 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004762 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 return false;
4764 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004765 if (DEBUG_FOCUS) {
4766 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4767 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004770 if (DEBUG_FOCUS) {
4771 ALOGD("Cannot transfer focus because windows are on different displays.");
4772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 return false;
4774 }
4775
4776 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004777 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4778 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004779 for (size_t i = 0; i < state.windows.size(); i++) {
4780 const TouchedWindow& touchedWindow = state.windows[i];
4781 if (touchedWindow.windowHandle == fromWindowHandle) {
4782 int32_t oldTargetFlags = touchedWindow.targetFlags;
4783 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004785 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 int32_t newTargetFlags = oldTargetFlags &
4788 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4789 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004790 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791
arthurhungb89ccb02020-12-30 16:19:01 +08004792 // Store the dragging window.
4793 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004794 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004795 }
4796
Jeff Brownf086ddb2014-02-11 14:28:48 -08004797 found = true;
4798 goto Found;
4799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 }
4801 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004804 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004805 if (DEBUG_FOCUS) {
4806 ALOGD("Focus transfer failed because from window did not have focus.");
4807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 return false;
4809 }
4810
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004811 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4812 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004813 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004814 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004815 CancelationOptions
4816 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4817 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004819 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 }
4821
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004822 if (DEBUG_FOCUS) {
4823 logDispatchStateLocked();
4824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 } // release lock
4826
4827 // Wake up poll loop since it may need to make new input dispatching choices.
4828 mLooper->wake();
4829 return true;
4830}
4831
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004832// Binder call
4833bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4834 sp<IBinder> fromToken;
4835 { // acquire lock
4836 std::scoped_lock _l(mLock);
4837
chaviw98318de2021-05-19 16:45:23 -05004838 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004839 if (toWindowHandle == nullptr) {
4840 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4841 return false;
4842 }
4843
4844 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4845
4846 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4847 if (touchStateIt == mTouchStatesByDisplay.end()) {
4848 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4849 displayId);
4850 return false;
4851 }
4852
4853 TouchState& state = touchStateIt->second;
4854 if (state.windows.size() != 1) {
4855 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4856 state.windows.size());
4857 return false;
4858 }
4859 const TouchedWindow& touchedWindow = state.windows[0];
4860 fromToken = touchedWindow.windowHandle->getToken();
4861 } // release lock
4862
4863 return transferTouchFocus(fromToken, destChannelToken);
4864}
4865
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004867 if (DEBUG_FOCUS) {
4868 ALOGD("Resetting and dropping all events (%s).", reason);
4869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870
4871 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4872 synthesizeCancelationEventsForAllConnectionsLocked(options);
4873
4874 resetKeyRepeatLocked();
4875 releasePendingEventLocked();
4876 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004880 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004882 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883}
4884
4885void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004886 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 dumpDispatchStateLocked(dump);
4888
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004889 std::istringstream stream(dump);
4890 std::string line;
4891
4892 while (std::getline(stream, line, '\n')) {
4893 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 }
4895}
4896
Prabir Pradhan99987712020-11-10 18:43:05 -08004897std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4898 std::string dump;
4899
4900 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4901 toString(mFocusedWindowRequestedPointerCapture));
4902
4903 std::string windowName = "None";
4904 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05004905 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004906 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4907 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4908 : "token has capture without window";
4909 }
4910 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4911
4912 return dump;
4913}
4914
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004915void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004916 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4917 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4918 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004919 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920
Tiger Huang721e26f2018-07-24 22:26:19 +08004921 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4922 dump += StringPrintf(INDENT "FocusedApplications:\n");
4923 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4924 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004925 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004926 const std::chrono::duration timeout =
4927 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004928 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004929 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004930 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004933 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004935
Vishnu Nairc519ff72021-01-21 08:23:08 -08004936 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004937 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004939 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004940 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004941 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4942 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004943 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004944 state.displayId, toString(state.down), toString(state.split),
4945 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004946 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004947 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004948 for (size_t i = 0; i < state.windows.size(); i++) {
4949 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004950 dump += StringPrintf(INDENT4
4951 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4952 i, touchedWindow.windowHandle->getName().c_str(),
4953 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004954 }
4955 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004956 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 }
4959 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004960 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961 }
4962
arthurhung6d4bed92021-03-17 11:59:33 +08004963 if (mDragState) {
4964 dump += StringPrintf(INDENT "DragState:\n");
4965 mDragState->dump(dump, INDENT2);
4966 }
4967
Arthur Hungb92218b2018-08-14 12:00:21 +08004968 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004969 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004970 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004971 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004972 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004973 dump += INDENT2 "Windows:\n";
4974 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05004975 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
4976 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004978 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004979 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004980 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004981 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004982 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004983 "applicationInfo.name=%s, "
4984 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004985 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004986 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004987 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004988 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004990 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004991 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004992 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004993 windowInfo->frameLeft, windowInfo->frameTop,
4994 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004995 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004996 windowInfo->applicationInfo.name.c_str(),
4997 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004998 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004999 dump += StringPrintf(", inputFeatures=%s",
5000 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005001 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005002 "ms, trustedOverlay=%s, hasToken=%s, "
5003 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005004 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005005 millis(windowInfo->dispatchingTimeout),
5006 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005007 toString(windowInfo->token != nullptr),
5008 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005009 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005010 }
5011 } else {
5012 dump += INDENT2 "Windows: <none>\n";
5013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005016 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 }
5018
Michael Wright3dd60e22019-03-27 22:06:44 +00005019 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005020 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005021 const std::vector<Monitor>& monitors = it.second;
5022 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5023 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005024 }
5025 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005026 const std::vector<Monitor>& monitors = it.second;
5027 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5028 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005031 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032 }
5033
5034 nsecs_t currentTime = now();
5035
5036 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005037 if (!mRecentQueue.empty()) {
5038 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005039 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005040 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005041 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005042 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 }
5044 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005045 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046 }
5047
5048 // Dump event currently being dispatched.
5049 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005050 dump += INDENT "PendingEvent:\n";
5051 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005052 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005053 dump += StringPrintf(", age=%" PRId64 "ms\n",
5054 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005056 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 }
5058
5059 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005060 if (!mInboundQueue.empty()) {
5061 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005062 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005063 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005064 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005065 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 }
5067 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005068 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 }
5070
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005071 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005072 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005073 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5074 const KeyReplacement& replacement = pair.first;
5075 int32_t newKeyCode = pair.second;
5076 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005077 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005078 }
5079 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005080 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005081 }
5082
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005083 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005084 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005085 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005086 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005087 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005088 connection->inputChannel->getFd().get(),
5089 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005090 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005093 if (!connection->outboundQueue.empty()) {
5094 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5095 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005096 dump += dumpQueue(connection->outboundQueue, currentTime);
5097
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005102 if (!connection->waitQueue.empty()) {
5103 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5104 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005105 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005107 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 }
5109 }
5110 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005111 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113
5114 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005115 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5116 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005118 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 }
5120
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005121 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005122 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5123 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5124 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005125 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005126 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127}
5128
Michael Wright3dd60e22019-03-27 22:06:44 +00005129void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5130 const size_t numMonitors = monitors.size();
5131 for (size_t i = 0; i < numMonitors; i++) {
5132 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005133 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005134 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5135 dump += "\n";
5136 }
5137}
5138
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005139class LooperEventCallback : public LooperCallback {
5140public:
5141 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5142 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5143
5144private:
5145 std::function<int(int events)> mCallback;
5146};
5147
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005148Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005149#if DEBUG_CHANNEL_CREATION
5150 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151#endif
5152
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005153 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005154 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005155 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005156
5157 if (result) {
5158 return base::Error(result) << "Failed to open input channel pair with name " << name;
5159 }
5160
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005162 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005163 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005164 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005165 sp<Connection> connection =
5166 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005168 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5169 ALOGE("Created a new connection, but the token %p is already known", token.get());
5170 }
5171 mConnectionsByToken.emplace(token, connection);
5172
5173 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5174 this, std::placeholders::_1, token);
5175
5176 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 } // release lock
5178
5179 // Wake the looper because some connections have changed.
5180 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005181 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182}
5183
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005184Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5185 bool isGestureMonitor,
5186 const std::string& name,
5187 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005188 std::shared_ptr<InputChannel> serverChannel;
5189 std::unique_ptr<InputChannel> clientChannel;
5190 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5191 if (result) {
5192 return base::Error(result) << "Failed to open input channel pair with name " << name;
5193 }
5194
Michael Wright3dd60e22019-03-27 22:06:44 +00005195 { // acquire lock
5196 std::scoped_lock _l(mLock);
5197
5198 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005199 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5200 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005201 }
5202
Garfield Tan15601662020-09-22 15:32:38 -07005203 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005204 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005205 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005206
5207 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5208 ALOGE("Created a new connection, but the token %p is already known", token.get());
5209 }
5210 mConnectionsByToken.emplace(token, connection);
5211 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5212 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005213
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005214 auto& monitorsByDisplay =
5215 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005216 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005217
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005218 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005219 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5220 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005221 }
Garfield Tan15601662020-09-22 15:32:38 -07005222
Michael Wright3dd60e22019-03-27 22:06:44 +00005223 // Wake the looper because some connections have changed.
5224 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005225 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005226}
5227
Garfield Tan15601662020-09-22 15:32:38 -07005228status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005230 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231
Garfield Tan15601662020-09-22 15:32:38 -07005232 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 if (status) {
5234 return status;
5235 }
5236 } // release lock
5237
5238 // Wake the poll loop because removing the connection may have changed the current
5239 // synchronization state.
5240 mLooper->wake();
5241 return OK;
5242}
5243
Garfield Tan15601662020-09-22 15:32:38 -07005244status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5245 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005246 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005247 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005248 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 return BAD_VALUE;
5250 }
5251
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005252 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005253
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005255 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 }
5257
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005258 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259
5260 nsecs_t currentTime = now();
5261 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5262
5263 connection->status = Connection::STATUS_ZOMBIE;
5264 return OK;
5265}
5266
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005267void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5268 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5269 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005270}
5271
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005272void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005273 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005274 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005275 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005276 std::vector<Monitor>& monitors = it->second;
5277 const size_t numMonitors = monitors.size();
5278 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005279 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005280 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5281 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005282 monitors.erase(monitors.begin() + i);
5283 break;
5284 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005285 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005286 if (monitors.empty()) {
5287 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005288 } else {
5289 ++it;
5290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 }
5292}
5293
Michael Wright3dd60e22019-03-27 22:06:44 +00005294status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5295 { // acquire lock
5296 std::scoped_lock _l(mLock);
5297 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5298
5299 if (!foundDisplayId) {
5300 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5301 return BAD_VALUE;
5302 }
5303 int32_t displayId = foundDisplayId.value();
5304
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005305 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5306 mTouchStatesByDisplay.find(displayId);
5307 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005308 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5309 return BAD_VALUE;
5310 }
5311
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005312 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005313 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005314 std::optional<int32_t> foundDeviceId;
5315 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005316 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005317 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005318 foundDeviceId = state.deviceId;
5319 }
5320 }
5321 if (!foundDeviceId || !state.down) {
5322 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005323 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005324 return BAD_VALUE;
5325 }
5326 int32_t deviceId = foundDeviceId.value();
5327
5328 // Send cancel events to all the input channels we're stealing from.
5329 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005330 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005331 options.deviceId = deviceId;
5332 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005333 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005334 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005335 std::shared_ptr<InputChannel> channel =
5336 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005337 if (channel != nullptr) {
5338 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005339 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005340 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005341 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005342 canceledWindows += "]";
5343 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5344 canceledWindows.c_str());
5345
Michael Wright3dd60e22019-03-27 22:06:44 +00005346 // Then clear the current touch state so we stop dispatching to them as well.
5347 state.filterNonMonitors();
5348 }
5349 return OK;
5350}
5351
Prabir Pradhan99987712020-11-10 18:43:05 -08005352void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5353 { // acquire lock
5354 std::scoped_lock _l(mLock);
5355 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005356 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005357 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5358 windowHandle != nullptr ? windowHandle->getName().c_str()
5359 : "token without window");
5360 }
5361
Vishnu Nairc519ff72021-01-21 08:23:08 -08005362 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005363 if (focusedToken != windowToken) {
5364 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5365 enabled ? "enable" : "disable");
5366 return;
5367 }
5368
5369 if (enabled == mFocusedWindowRequestedPointerCapture) {
5370 ALOGW("Ignoring request to %s Pointer Capture: "
5371 "window has %s requested pointer capture.",
5372 enabled ? "enable" : "disable", enabled ? "already" : "not");
5373 return;
5374 }
5375
5376 mFocusedWindowRequestedPointerCapture = enabled;
5377 setPointerCaptureLocked(enabled);
5378 } // release lock
5379
5380 // Wake the thread to process command entries.
5381 mLooper->wake();
5382}
5383
Michael Wright3dd60e22019-03-27 22:06:44 +00005384std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5385 const sp<IBinder>& token) {
5386 for (const auto& it : mGestureMonitorsByDisplay) {
5387 const std::vector<Monitor>& monitors = it.second;
5388 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005389 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005390 return it.first;
5391 }
5392 }
5393 }
5394 return std::nullopt;
5395}
5396
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005397std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5398 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5399 if (gesturePid.has_value()) {
5400 return gesturePid;
5401 }
5402 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5403}
5404
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005405sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005406 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005407 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005408 }
5409
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005410 for (const auto& [token, connection] : mConnectionsByToken) {
5411 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005412 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 }
5414 }
Robert Carr4e670e52018-08-15 13:26:12 -07005415
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005416 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417}
5418
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005419std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5420 sp<Connection> connection = getConnectionLocked(connectionToken);
5421 if (connection == nullptr) {
5422 return "<nullptr>";
5423 }
5424 return connection->getInputChannelName();
5425}
5426
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005427void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005428 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005429 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005430}
5431
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005432void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5433 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005434 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005435 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5436 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 commandEntry->connection = connection;
5438 commandEntry->eventTime = currentTime;
5439 commandEntry->seq = seq;
5440 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005441 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005442 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443}
5444
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005445void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5446 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005448 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005450 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5451 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005453 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454}
5455
Vishnu Nairad321cd2020-08-20 16:40:21 -07005456void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5457 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005458 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5459 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005460 commandEntry->oldToken = oldToken;
5461 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005462 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005463}
5464
arthurhungf452d0b2021-01-06 00:19:52 +08005465void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5466 std::unique_ptr<CommandEntry> commandEntry =
5467 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5468 commandEntry->newToken = token;
5469 commandEntry->x = x;
5470 commandEntry->y = y;
5471 postCommandLocked(std::move(commandEntry));
5472}
5473
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005474void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5475 if (connection == nullptr) {
5476 LOG_ALWAYS_FATAL("Caller must check for nullness");
5477 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005478 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5479 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005480 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005481 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005482 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005483 return;
5484 }
5485 /**
5486 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5487 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5488 * has changed. This could cause newer entries to time out before the already dispatched
5489 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5490 * processes the events linearly. So providing information about the oldest entry seems to be
5491 * most useful.
5492 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005493 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005494 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5495 std::string reason =
5496 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005497 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005498 ns2ms(currentWait),
5499 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005500 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005501 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005502
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005503 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5504
5505 // Stop waking up for events on this connection, it is already unresponsive
5506 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005507}
5508
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005509void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5510 std::string reason =
5511 StringPrintf("%s does not have a focused window", application->getName().c_str());
5512 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005513
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005514 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5515 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5516 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005517 postCommandLocked(std::move(commandEntry));
5518}
5519
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005520void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5521 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5522 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5523 commandEntry->obscuringPackage = obscuringPackage;
5524 postCommandLocked(std::move(commandEntry));
5525}
5526
chaviw98318de2021-05-19 16:45:23 -05005527void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005528 const std::string& reason) {
5529 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5530 updateLastAnrStateLocked(windowLabel, reason);
5531}
5532
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005533void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5534 const std::string& reason) {
5535 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005536 updateLastAnrStateLocked(windowLabel, reason);
5537}
5538
5539void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5540 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005542 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 struct tm tm;
5544 localtime_r(&t, &tm);
5545 char timestr[64];
5546 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005547 mLastAnrState.clear();
5548 mLastAnrState += INDENT "ANR:\n";
5549 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005550 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5551 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005552 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553}
5554
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005555void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 mLock.unlock();
5557
5558 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5559
5560 mLock.lock();
5561}
5562
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005563void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 sp<Connection> connection = commandEntry->connection;
5565
5566 if (connection->status != Connection::STATUS_ZOMBIE) {
5567 mLock.unlock();
5568
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005569 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570
5571 mLock.lock();
5572 }
5573}
5574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005575void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005576 sp<IBinder> oldToken = commandEntry->oldToken;
5577 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005578 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005579 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005580 mLock.lock();
5581}
5582
arthurhungf452d0b2021-01-06 00:19:52 +08005583void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5584 sp<IBinder> newToken = commandEntry->newToken;
5585 mLock.unlock();
5586 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5587 mLock.lock();
5588}
5589
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005590void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005592
5593 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5594
5595 mLock.lock();
5596}
5597
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005598void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005599 mLock.unlock();
5600
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005601 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
5603 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005604}
5605
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005606void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005607 mLock.unlock();
5608
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005609 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5610
5611 mLock.lock();
5612}
5613
5614void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5615 mLock.unlock();
5616
5617 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5618
5619 mLock.lock();
5620}
5621
5622void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5623 mLock.unlock();
5624
5625 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005626
5627 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005628}
5629
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005630void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5631 mLock.unlock();
5632
5633 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5634
5635 mLock.lock();
5636}
5637
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5639 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005640 KeyEntry& entry = *(commandEntry->keyEntry);
5641 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642
5643 mLock.unlock();
5644
Michael Wright2b3c3302018-03-02 17:19:13 +00005645 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005646 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005647 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005648 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5649 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005650 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652
5653 mLock.lock();
5654
5655 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005656 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005658 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005660 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5661 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663}
5664
chaviwfd6d3512019-03-25 13:23:49 -07005665void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5666 mLock.unlock();
5667 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5668 mLock.lock();
5669}
5670
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005671/**
5672 * Connection is responsive if it has no events in the waitQueue that are older than the
5673 * current time.
5674 */
5675static bool isConnectionResponsive(const Connection& connection) {
5676 const nsecs_t currentTime = now();
5677 for (const DispatchEntry* entry : connection.waitQueue) {
5678 if (entry->timeoutTime < currentTime) {
5679 return false;
5680 }
5681 }
5682 return true;
5683}
5684
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005685void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005687 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005689 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690
5691 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005692 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005693 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005694 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005696 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005697 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005698 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005699 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5700 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005701 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005702 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5703 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5704 connection->inputChannel->getConnectionToken(),
5705 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5706 finishTime);
5707 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005708
5709 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005710 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005711 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005712 restartEvent =
5713 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005714 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005715 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005716 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5717 handled);
5718 } else {
5719 restartEvent = false;
5720 }
5721
5722 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005723 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005724 // contents of the wait queue to have been drained, so we need to double-check
5725 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005726 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5727 if (dispatchEntryIt != connection->waitQueue.end()) {
5728 dispatchEntry = *dispatchEntryIt;
5729 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005730 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5731 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005732 if (!connection->responsive) {
5733 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005734 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005735 // The connection was unresponsive, and now it's responsive.
5736 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005737 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005738 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005739 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005740 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005741 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005742 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005743 } else {
5744 releaseDispatchEntry(dispatchEntry);
5745 }
5746 }
5747
5748 // Start the next dispatch cycle for this connection.
5749 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750}
5751
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005752void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5753 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5754 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5755 monitorUnresponsiveCommand->pid = pid;
5756 monitorUnresponsiveCommand->reason = std::move(reason);
5757 postCommandLocked(std::move(monitorUnresponsiveCommand));
5758}
5759
5760void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5761 std::string reason) {
5762 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5763 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5764 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5765 windowUnresponsiveCommand->reason = std::move(reason);
5766 postCommandLocked(std::move(windowUnresponsiveCommand));
5767}
5768
5769void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5770 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5771 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5772 monitorResponsiveCommand->pid = pid;
5773 postCommandLocked(std::move(monitorResponsiveCommand));
5774}
5775
5776void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5777 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5778 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5779 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5780 postCommandLocked(std::move(windowResponsiveCommand));
5781}
5782
5783/**
5784 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5785 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5786 * command entry to the command queue.
5787 */
5788void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5789 std::string reason) {
5790 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5791 if (connection.monitor) {
5792 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5793 reason.c_str());
5794 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5795 if (!pid.has_value()) {
5796 ALOGE("Could not find unresponsive monitor for connection %s",
5797 connection.inputChannel->getName().c_str());
5798 return;
5799 }
5800 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5801 return;
5802 }
5803 // If not a monitor, must be a window
5804 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5805 reason.c_str());
5806 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5807}
5808
5809/**
5810 * Tell the policy that a connection has become responsive so that it can stop ANR.
5811 */
5812void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5813 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5814 if (connection.monitor) {
5815 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5816 if (!pid.has_value()) {
5817 ALOGE("Could not find responsive monitor for connection %s",
5818 connection.inputChannel->getName().c_str());
5819 return;
5820 }
5821 sendMonitorResponsiveCommandLocked(pid.value());
5822 return;
5823 }
5824 // If not a monitor, must be a window
5825 sendWindowResponsiveCommandLocked(connectionToken);
5826}
5827
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005829 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005830 KeyEntry& keyEntry, bool handled) {
5831 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005832 if (!handled) {
5833 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005834 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005835 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005836 return false;
5837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005839 // Get the fallback key state.
5840 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005841 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005842 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005843 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005844 connection->inputState.removeFallbackKey(originalKeyCode);
5845 }
5846
5847 if (handled || !dispatchEntry->hasForegroundTarget()) {
5848 // If the application handles the original key for which we previously
5849 // generated a fallback or if the window is not a foreground window,
5850 // then cancel the associated fallback key, if any.
5851 if (fallbackKeyCode != -1) {
5852 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005854 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005855 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005856 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005858 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005859 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860
5861 mLock.unlock();
5862
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005863 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005864 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865
5866 mLock.lock();
5867
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005868 // Cancel the fallback key.
5869 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005871 "application handled the original non-fallback key "
5872 "or is no longer a foreground target, "
5873 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 options.keyCode = fallbackKeyCode;
5875 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005876 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005877 connection->inputState.removeFallbackKey(originalKeyCode);
5878 }
5879 } else {
5880 // If the application did not handle a non-fallback key, first check
5881 // that we are in a good state to perform unhandled key event processing
5882 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005883 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005884 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005886 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005887 "since this is not an initial down. "
5888 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005889 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005891 return false;
5892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005894 // Dispatch the unhandled key to the policy.
5895#if DEBUG_OUTBOUND_EVENT_DETAILS
5896 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005897 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005898 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005899#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005900 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005901
5902 mLock.unlock();
5903
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005904 bool fallback =
5905 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005906 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005907
5908 mLock.lock();
5909
5910 if (connection->status != Connection::STATUS_NORMAL) {
5911 connection->inputState.removeFallbackKey(originalKeyCode);
5912 return false;
5913 }
5914
5915 // Latch the fallback keycode for this key on an initial down.
5916 // The fallback keycode cannot change at any other point in the lifecycle.
5917 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005919 fallbackKeyCode = event.getKeyCode();
5920 } else {
5921 fallbackKeyCode = AKEYCODE_UNKNOWN;
5922 }
5923 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5924 }
5925
5926 ALOG_ASSERT(fallbackKeyCode != -1);
5927
5928 // Cancel the fallback key if the policy decides not to send it anymore.
5929 // We will continue to dispatch the key to the policy but we will no
5930 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005931 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5932 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005933#if DEBUG_OUTBOUND_EVENT_DETAILS
5934 if (fallback) {
5935 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005936 "as a fallback for %d, but on the DOWN it had requested "
5937 "to send %d instead. Fallback canceled.",
5938 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005939 } else {
5940 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005941 "but on the DOWN it had requested to send %d. "
5942 "Fallback canceled.",
5943 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005944 }
5945#endif
5946
5947 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5948 "canceling fallback, policy no longer desires it");
5949 options.keyCode = fallbackKeyCode;
5950 synthesizeCancelationEventsForConnectionLocked(connection, options);
5951
5952 fallback = false;
5953 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005954 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005955 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956 }
5957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958
5959#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005960 {
5961 std::string msg;
5962 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5963 connection->inputState.getFallbackKeys();
5964 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005965 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005967 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005968 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005969 }
5970#endif
5971
5972 if (fallback) {
5973 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005974 keyEntry.eventTime = event.getEventTime();
5975 keyEntry.deviceId = event.getDeviceId();
5976 keyEntry.source = event.getSource();
5977 keyEntry.displayId = event.getDisplayId();
5978 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5979 keyEntry.keyCode = fallbackKeyCode;
5980 keyEntry.scanCode = event.getScanCode();
5981 keyEntry.metaState = event.getMetaState();
5982 keyEntry.repeatCount = event.getRepeatCount();
5983 keyEntry.downTime = event.getDownTime();
5984 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985
5986#if DEBUG_OUTBOUND_EVENT_DETAILS
5987 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005988 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005989 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005990#endif
5991 return true; // restart the event
5992 } else {
5993#if DEBUG_OUTBOUND_EVENT_DETAILS
5994 ALOGD("Unhandled key event: No fallback key.");
5995#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005996
5997 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005998 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005999 }
6000 }
6001 return false;
6002}
6003
6004bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006005 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006006 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007 return false;
6008}
6009
6010void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6011 mLock.unlock();
6012
Sean Stoutb4e0a592021-02-23 07:34:53 -08006013 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6014 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015
6016 mLock.lock();
6017}
6018
Michael Wrightd02c5b62014-02-10 15:10:22 -08006019void InputDispatcher::traceInboundQueueLengthLocked() {
6020 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006021 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022 }
6023}
6024
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006025void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026 if (ATRACE_ENABLED()) {
6027 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006028 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6029 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030 }
6031}
6032
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006033void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034 if (ATRACE_ENABLED()) {
6035 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006036 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6037 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 }
6039}
6040
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006041void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006042 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006044 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 dumpDispatchStateLocked(dump);
6046
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006047 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006048 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006049 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 }
6051}
6052
6053void InputDispatcher::monitor() {
6054 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006055 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006057 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006058}
6059
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006060/**
6061 * Wake up the dispatcher and wait until it processes all events and commands.
6062 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6063 * this method can be safely called from any thread, as long as you've ensured that
6064 * the work you are interested in completing has already been queued.
6065 */
6066bool InputDispatcher::waitForIdle() {
6067 /**
6068 * Timeout should represent the longest possible time that a device might spend processing
6069 * events and commands.
6070 */
6071 constexpr std::chrono::duration TIMEOUT = 100ms;
6072 std::unique_lock lock(mLock);
6073 mLooper->wake();
6074 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6075 return result == std::cv_status::no_timeout;
6076}
6077
Vishnu Naire798b472020-07-23 13:52:21 -07006078/**
6079 * Sets focus to the window identified by the token. This must be called
6080 * after updating any input window handles.
6081 *
6082 * Params:
6083 * request.token - input channel token used to identify the window that should gain focus.
6084 * request.focusedToken - the token that the caller expects currently to be focused. If the
6085 * specified token does not match the currently focused window, this request will be dropped.
6086 * If the specified focused token matches the currently focused window, the call will succeed.
6087 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6088 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6089 * when requesting the focus change. This determines which request gets
6090 * precedence if there is a focus change request from another source such as pointer down.
6091 */
Vishnu Nair958da932020-08-21 17:12:37 -07006092void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6093 { // acquire lock
6094 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006095 std::optional<FocusResolver::FocusChanges> changes =
6096 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6097 if (changes) {
6098 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006099 }
6100 } // release lock
6101 // Wake up poll loop since it may need to make new input dispatching choices.
6102 mLooper->wake();
6103}
6104
Vishnu Nairc519ff72021-01-21 08:23:08 -08006105void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6106 if (changes.oldFocus) {
6107 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006108 if (focusedInputChannel) {
6109 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6110 "focus left window");
6111 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006112 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006113 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006114 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006115 if (changes.newFocus) {
6116 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006117 }
6118
Prabir Pradhan99987712020-11-10 18:43:05 -08006119 // If a window has pointer capture, then it must have focus. We need to ensure that this
6120 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6121 // If the window loses focus before it loses pointer capture, then the window can be in a state
6122 // where it has pointer capture but not focus, violating the contract. Therefore we must
6123 // dispatch the pointer capture event before the focus event. Since focus events are added to
6124 // the front of the queue (above), we add the pointer capture event to the front of the queue
6125 // after the focus events are added. This ensures the pointer capture event ends up at the
6126 // front.
6127 disablePointerCaptureForcedLocked();
6128
Vishnu Nairc519ff72021-01-21 08:23:08 -08006129 if (mFocusedDisplayId == changes.displayId) {
6130 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006131 }
6132}
Vishnu Nair958da932020-08-21 17:12:37 -07006133
Prabir Pradhan99987712020-11-10 18:43:05 -08006134void InputDispatcher::disablePointerCaptureForcedLocked() {
6135 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6136 return;
6137 }
6138
6139 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6140
6141 if (mFocusedWindowRequestedPointerCapture) {
6142 mFocusedWindowRequestedPointerCapture = false;
6143 setPointerCaptureLocked(false);
6144 }
6145
6146 if (!mWindowTokenWithPointerCapture) {
6147 // No need to send capture changes because no window has capture.
6148 return;
6149 }
6150
6151 if (mPendingEvent != nullptr) {
6152 // Move the pending event to the front of the queue. This will give the chance
6153 // for the pending event to be dropped if it is a captured event.
6154 mInboundQueue.push_front(mPendingEvent);
6155 mPendingEvent = nullptr;
6156 }
6157
6158 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6159 false /* hasCapture */);
6160 mInboundQueue.push_front(std::move(entry));
6161}
6162
Prabir Pradhan99987712020-11-10 18:43:05 -08006163void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6164 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6165 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6166 commandEntry->enabled = enabled;
6167 postCommandLocked(std::move(commandEntry));
6168}
6169
6170void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6171 android::inputdispatcher::CommandEntry* commandEntry) {
6172 mLock.unlock();
6173
6174 mPolicy->setPointerCapture(commandEntry->enabled);
6175
6176 mLock.lock();
6177}
6178
Vishnu Nair599f1412021-06-21 10:39:58 -07006179void InputDispatcher::displayRemoved(int32_t displayId) {
6180 { // acquire lock
6181 std::scoped_lock _l(mLock);
6182 // Set an empty list to remove all handles from the specific display.
6183 setInputWindowsLocked(/* window handles */ {}, displayId);
6184 setFocusedApplicationLocked(displayId, nullptr);
6185 // Call focus resolver to clean up stale requests. This must be called after input windows
6186 // have been removed for the removed display.
6187 mFocusResolver.displayRemoved(displayId);
6188 } // release lock
6189
6190 // Wake up poll loop since it may need to make new input dispatching choices.
6191 mLooper->wake();
6192}
6193
Garfield Tane84e6f92019-08-29 17:28:41 -07006194} // namespace android::inputdispatcher