blob: d16c9914297f5c56903dba6efb7d91530815a621 [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 Vishniakou363e7292021-07-09 03:22:42 +00003866 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3867 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3868 !mInputFilterEnabled) {
3869 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3870 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3871 }
3872
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003873 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 mLock.unlock();
3875 } // release lock
3876
3877 if (needWake) {
3878 mLooper->wake();
3879 }
3880}
3881
Chris Yef59a2f42020-10-16 12:55:26 -07003882void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3883#if DEBUG_INBOUND_EVENT_DETAILS
3884 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3885 " sensorType=%s",
3886 args->id, args->eventTime, args->deviceId, args->source,
3887 NamedEnum::string(args->sensorType).c_str());
3888#endif
3889
3890 bool needWake;
3891 { // acquire lock
3892 mLock.lock();
3893
3894 // Just enqueue a new sensor event.
3895 std::unique_ptr<SensorEntry> newEntry =
3896 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3897 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3898 args->sensorType, args->accuracy,
3899 args->accuracyChanged, args->values);
3900
3901 needWake = enqueueInboundEventLocked(std::move(newEntry));
3902 mLock.unlock();
3903 } // release lock
3904
3905 if (needWake) {
3906 mLooper->wake();
3907 }
3908}
3909
Chris Yefb552902021-02-03 17:18:37 -08003910void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3911#if DEBUG_INBOUND_EVENT_DETAILS
3912 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3913 args->deviceId, args->isOn);
3914#endif
3915 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3916}
3917
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003919 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920}
3921
3922void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3923#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003924 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003925 "switchMask=0x%08x",
3926 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927#endif
3928
3929 uint32_t policyFlags = args->policyFlags;
3930 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003931 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932}
3933
3934void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3935#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003936 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3937 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938#endif
3939
3940 bool needWake;
3941 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003942 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003944 std::unique_ptr<DeviceResetEntry> newEntry =
3945 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3946 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 } // release lock
3948
3949 if (needWake) {
3950 mLooper->wake();
3951 }
3952}
3953
Prabir Pradhan7e186182020-11-10 13:56:45 -08003954void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3955#if DEBUG_INBOUND_EVENT_DETAILS
3956 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3957 args->enabled ? "true" : "false");
3958#endif
3959
Prabir Pradhan99987712020-11-10 18:43:05 -08003960 bool needWake;
3961 { // acquire lock
3962 std::scoped_lock _l(mLock);
3963 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3964 args->enabled);
3965 needWake = enqueueInboundEventLocked(std::move(entry));
3966 } // release lock
3967
3968 if (needWake) {
3969 mLooper->wake();
3970 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003971}
3972
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003973InputEventInjectionResult InputDispatcher::injectInputEvent(
3974 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3975 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976#if DEBUG_INBOUND_EVENT_DETAILS
3977 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003978 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3979 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003981 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982
3983 policyFlags |= POLICY_FLAG_INJECTED;
3984 if (hasInjectionPermission(injectorPid, injectorUid)) {
3985 policyFlags |= POLICY_FLAG_TRUSTED;
3986 }
3987
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003988 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003989 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
3990 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
3991 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
3992 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
3993 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003994 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003995 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003996 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003997 }
3998
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003999 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004001 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004002 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4003 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004005 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004008 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004009 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4010 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4011 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004012 int32_t keyCode = incomingKey.getKeyCode();
4013 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004014 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004016 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004017 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004018 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4019 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4020 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4023 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004024 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025
4026 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4027 android::base::Timer t;
4028 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4029 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4030 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4031 std::to_string(t.duration().count()).c_str());
4032 }
4033 }
4034
4035 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 std::unique_ptr<KeyEntry> injectedEntry =
4037 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004038 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004039 incomingKey.getDisplayId(), policyFlags, action,
4040 flags, keyCode, incomingKey.getScanCode(), metaState,
4041 incomingKey.getRepeatCount(),
4042 incomingKey.getDownTime());
4043 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004044 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 }
4046
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004048 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4049 int32_t action = motionEvent.getAction();
4050 size_t pointerCount = motionEvent.getPointerCount();
4051 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4052 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004053 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004054 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004056 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004057 }
4058
4059 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004060 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061 android::base::Timer t;
4062 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4063 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4064 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4065 std::to_string(t.duration().count()).c_str());
4066 }
4067 }
4068
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004069 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4070 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4071 }
4072
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004074 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4075 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004076 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004077 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4078 resolvedDeviceId, motionEvent.getSource(),
4079 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004080 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004081 motionEvent.getButtonState(),
4082 motionEvent.getClassification(),
4083 motionEvent.getEdgeFlags(),
4084 motionEvent.getXPrecision(),
4085 motionEvent.getYPrecision(),
4086 motionEvent.getRawXCursorPosition(),
4087 motionEvent.getRawYCursorPosition(),
4088 motionEvent.getDownTime(), uint32_t(pointerCount),
4089 pointerProperties, samplePointerCoords,
4090 motionEvent.getXOffset(),
4091 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004092 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004093 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 sampleEventTimes += 1;
4095 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004096 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004097 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4098 resolvedDeviceId, motionEvent.getSource(),
4099 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004100 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004101 motionEvent.getMetaState(),
4102 motionEvent.getButtonState(),
4103 motionEvent.getClassification(),
4104 motionEvent.getEdgeFlags(),
4105 motionEvent.getXPrecision(),
4106 motionEvent.getYPrecision(),
4107 motionEvent.getRawXCursorPosition(),
4108 motionEvent.getRawYCursorPosition(),
4109 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004110 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004111 samplePointerCoords, motionEvent.getXOffset(),
4112 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004113 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004114 }
4115 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004119 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004120 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 }
4122
4123 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004124 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 injectionState->injectionIsAsync = true;
4126 }
4127
4128 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004129 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
4131 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004132 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004133 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004134 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 }
4136
4137 mLock.unlock();
4138
4139 if (needWake) {
4140 mLooper->wake();
4141 }
4142
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004143 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004145 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004147 if (syncMode == InputEventInjectionSync::NONE) {
4148 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 } else {
4150 for (;;) {
4151 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004152 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 break;
4154 }
4155
4156 nsecs_t remainingTimeout = endTime - now();
4157 if (remainingTimeout <= 0) {
4158#if DEBUG_INJECTION
4159 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004162 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 break;
4164 }
4165
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004166 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 }
4168
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004169 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4170 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 while (injectionState->pendingForegroundDispatches != 0) {
4172#if DEBUG_INJECTION
4173 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175#endif
4176 nsecs_t remainingTimeout = endTime - now();
4177 if (remainingTimeout <= 0) {
4178#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004179 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4180 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004182 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 break;
4184 }
4185
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004186 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 }
4188 }
4189 }
4190
4191 injectionState->release();
4192 } // release lock
4193
4194#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004195 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197#endif
4198
4199 return injectionResult;
4200}
4201
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004202std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004203 std::array<uint8_t, 32> calculatedHmac;
4204 std::unique_ptr<VerifiedInputEvent> result;
4205 switch (event.getType()) {
4206 case AINPUT_EVENT_TYPE_KEY: {
4207 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4208 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4209 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004210 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004211 break;
4212 }
4213 case AINPUT_EVENT_TYPE_MOTION: {
4214 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4215 VerifiedMotionEvent verifiedMotionEvent =
4216 verifiedMotionEventFromMotionEvent(motionEvent);
4217 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004218 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004219 break;
4220 }
4221 default: {
4222 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4223 return nullptr;
4224 }
4225 }
4226 if (calculatedHmac == INVALID_HMAC) {
4227 return nullptr;
4228 }
4229 if (calculatedHmac != event.getHmac()) {
4230 return nullptr;
4231 }
4232 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004233}
4234
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 return injectorUid == 0 ||
4237 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238}
4239
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004240void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004241 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004242 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 if (injectionState) {
4244#if DEBUG_INJECTION
4245 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 "injectorPid=%d, injectorUid=%d",
4247 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248#endif
4249
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004250 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 // Log the outcome since the injector did not wait for the injection result.
4252 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004253 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 ALOGV("Asynchronous input event injection succeeded.");
4255 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004256 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 ALOGW("Asynchronous input event injection failed.");
4258 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004259 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 ALOGW("Asynchronous input event injection permission denied.");
4261 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004262 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 ALOGW("Asynchronous input event injection timed out.");
4264 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004265 case InputEventInjectionResult::PENDING:
4266 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4267 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269 }
4270
4271 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004272 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274}
4275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4277 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 if (injectionState) {
4279 injectionState->pendingForegroundDispatches += 1;
4280 }
4281}
4282
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004283void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4284 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 if (injectionState) {
4286 injectionState->pendingForegroundDispatches -= 1;
4287
4288 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004289 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291 }
4292}
4293
chaviw98318de2021-05-19 16:45:23 -05004294const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004295 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004296 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004297 auto it = mWindowHandlesByDisplay.find(displayId);
4298 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004299}
4300
chaviw98318de2021-05-19 16:45:23 -05004301sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004302 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004303 if (windowHandleToken == nullptr) {
4304 return nullptr;
4305 }
4306
Arthur Hungb92218b2018-08-14 12:00:21 +08004307 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004308 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4309 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004310 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004311 return windowHandle;
4312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004315 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316}
4317
chaviw98318de2021-05-19 16:45:23 -05004318sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4319 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004320 if (windowHandleToken == nullptr) {
4321 return nullptr;
4322 }
4323
chaviw98318de2021-05-19 16:45:23 -05004324 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004325 if (windowHandle->getToken() == windowHandleToken) {
4326 return windowHandle;
4327 }
4328 }
4329 return nullptr;
4330}
4331
chaviw98318de2021-05-19 16:45:23 -05004332sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4333 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004334 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004335 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4336 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004337 if (handle->getId() == windowHandle->getId() &&
4338 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004339 if (windowHandle->getInfo()->displayId != it.first) {
4340 ALOGE("Found window %s in display %" PRId32
4341 ", but it should belong to display %" PRId32,
4342 windowHandle->getName().c_str(), it.first,
4343 windowHandle->getInfo()->displayId);
4344 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004345 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 }
4348 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004349 return nullptr;
4350}
4351
chaviw98318de2021-05-19 16:45:23 -05004352sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004353 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4354 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355}
4356
chaviw98318de2021-05-19 16:45:23 -05004357bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004358 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4359 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004360 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004361 if (connection != nullptr && noInputChannel) {
4362 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4363 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4364 return false;
4365 }
4366
4367 if (connection == nullptr) {
4368 if (!noInputChannel) {
4369 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4370 }
4371 return false;
4372 }
4373 if (!connection->responsive) {
4374 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4375 return false;
4376 }
4377 return true;
4378}
4379
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004380std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4381 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004382 auto connectionIt = mConnectionsByToken.find(token);
4383 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004384 return nullptr;
4385 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004386 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004387}
4388
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004389void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004390 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4391 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004392 // Remove all handles on a display if there are no windows left.
4393 mWindowHandlesByDisplay.erase(displayId);
4394 return;
4395 }
4396
4397 // Since we compare the pointer of input window handles across window updates, we need
4398 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004399 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4400 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4401 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004402 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004403 }
4404
chaviw98318de2021-05-19 16:45:23 -05004405 std::vector<sp<WindowInfoHandle>> newHandles;
4406 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004407 if (!handle->updateInfo()) {
4408 // handle no longer valid
4409 continue;
4410 }
4411
chaviw98318de2021-05-19 16:45:23 -05004412 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004413 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004414 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004415 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4416 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4417 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004418 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004419 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004420 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004421 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004422 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004423 }
4424
4425 if (info->displayId != displayId) {
4426 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4427 handle->getName().c_str(), displayId, info->displayId);
4428 continue;
4429 }
4430
Robert Carredd13602020-04-13 17:24:34 -07004431 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4432 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004433 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004434 oldHandle->updateFrom(handle);
4435 newHandles.push_back(oldHandle);
4436 } else {
4437 newHandles.push_back(handle);
4438 }
4439 }
4440
4441 // Insert or replace
4442 mWindowHandlesByDisplay[displayId] = newHandles;
4443}
4444
Arthur Hung72d8dc32020-03-28 00:48:39 +00004445void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004446 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004447 { // acquire lock
4448 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004449 for (const auto& [displayId, handles] : handlesPerDisplay) {
4450 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004451 }
4452 }
4453 // Wake up poll loop since it may need to make new input dispatching choices.
4454 mLooper->wake();
4455}
4456
Arthur Hungb92218b2018-08-14 12:00:21 +08004457/**
4458 * Called from InputManagerService, update window handle list by displayId that can receive input.
4459 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4460 * If set an empty list, remove all handles from the specific display.
4461 * For focused handle, check if need to change and send a cancel event to previous one.
4462 * For removed handle, check if need to send a cancel event if already in touch.
4463 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004464void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004465 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004466 if (DEBUG_FOCUS) {
4467 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004468 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004469 windowList += iwh->getName() + " ";
4470 }
4471 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004474 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004475 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004476 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004477 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004478 if (noInputWindow && window->getToken() != nullptr) {
4479 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4480 window->getName().c_str());
4481 window->releaseChannel();
4482 }
4483 }
4484
Arthur Hung72d8dc32020-03-28 00:48:39 +00004485 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004486 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004488 // Save the old windows' orientation by ID before it gets updated.
4489 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004490 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004491 oldWindowOrientations.emplace(handle->getId(),
4492 handle->getInfo()->transform.getOrientation());
4493 }
4494
chaviw98318de2021-05-19 16:45:23 -05004495 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004496
chaviw98318de2021-05-19 16:45:23 -05004497 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004498 if (mLastHoverWindowHandle &&
4499 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4500 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004501 mLastHoverWindowHandle = nullptr;
4502 }
4503
Vishnu Nairc519ff72021-01-21 08:23:08 -08004504 std::optional<FocusResolver::FocusChanges> changes =
4505 mFocusResolver.setInputWindows(displayId, windowHandles);
4506 if (changes) {
4507 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004510 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4511 mTouchStatesByDisplay.find(displayId);
4512 if (stateIt != mTouchStatesByDisplay.end()) {
4513 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004514 for (size_t i = 0; i < state.windows.size();) {
4515 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004516 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004517 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004518 ALOGD("Touched window was removed: %s in display %" PRId32,
4519 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004520 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004521 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004522 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4523 if (touchedInputChannel != nullptr) {
4524 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4525 "touched window was removed");
4526 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004528 state.windows.erase(state.windows.begin() + i);
4529 } else {
4530 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 }
4532 }
arthurhungb89ccb02020-12-30 16:19:01 +08004533
arthurhung6d4bed92021-03-17 11:59:33 +08004534 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004535 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004536 if (mDragState &&
4537 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004538 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004539 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004540 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004541 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004542
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004543 if (isPerWindowInputRotationEnabled()) {
4544 // Determine if the orientation of any of the input windows have changed, and cancel all
4545 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004546 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4547 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004548 if (newWindowHandle != nullptr &&
4549 newWindowHandle->getInfo()->transform.getOrientation() !=
4550 oldWindowOrientations[oldWindowHandle->getId()]) {
4551 std::shared_ptr<InputChannel> inputChannel =
4552 getInputChannelLocked(newWindowHandle->getToken());
4553 if (inputChannel != nullptr) {
4554 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4555 "touched window's orientation changed");
4556 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4557 }
4558 }
4559 }
4560 }
4561
Arthur Hung72d8dc32020-03-28 00:48:39 +00004562 // Release information for windows that are no longer present.
4563 // This ensures that unused input channels are released promptly.
4564 // Otherwise, they might stick around until the window handle is destroyed
4565 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004566 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004567 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004568 if (DEBUG_FOCUS) {
4569 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004570 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004571 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004572 // To avoid making too many calls into the compat framework, only
4573 // check for window flags when windows are going away.
4574 // TODO(b/157929241) : delete this. This is only needed temporarily
4575 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004576 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004577 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4578 oldWindowHandle->getName().c_str());
4579 if (mCompatService != nullptr) {
4580 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4581 oldWindowHandle->getInfo()->ownerUid);
4582 }
4583 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004584 }
chaviw291d88a2019-02-14 10:33:58 -08004585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586}
4587
4588void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004589 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004590 if (DEBUG_FOCUS) {
4591 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4592 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4593 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004594 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004595 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004596 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 } // release lock
4598
4599 // Wake up poll loop since it may need to make new input dispatching choices.
4600 mLooper->wake();
4601}
4602
Vishnu Nair599f1412021-06-21 10:39:58 -07004603void InputDispatcher::setFocusedApplicationLocked(
4604 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4605 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4606 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4607
4608 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4609 return; // This application is already focused. No need to wake up or change anything.
4610 }
4611
4612 // Set the new application handle.
4613 if (inputApplicationHandle != nullptr) {
4614 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4615 } else {
4616 mFocusedApplicationHandlesByDisplay.erase(displayId);
4617 }
4618
4619 // No matter what the old focused application was, stop waiting on it because it is
4620 // no longer focused.
4621 resetNoFocusedWindowTimeoutLocked();
4622}
4623
Tiger Huang721e26f2018-07-24 22:26:19 +08004624/**
4625 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4626 * the display not specified.
4627 *
4628 * We track any unreleased events for each window. If a window loses the ability to receive the
4629 * released event, we will send a cancel event to it. So when the focused display is changed, we
4630 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4631 * display. The display-specified events won't be affected.
4632 */
4633void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004634 if (DEBUG_FOCUS) {
4635 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4636 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004637 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004638 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004639
4640 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004641 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004642 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004643 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004644 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004645 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004646 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004647 CancelationOptions
4648 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4649 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004650 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004651 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4652 }
4653 }
4654 mFocusedDisplayId = displayId;
4655
Chris Ye3c2d6f52020-08-09 10:39:48 -07004656 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004657 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004658 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004659
Vishnu Nairad321cd2020-08-20 16:40:21 -07004660 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004661 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004662 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004663 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004664 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004665 }
4666 }
4667 }
4668
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004669 if (DEBUG_FOCUS) {
4670 logDispatchStateLocked();
4671 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004672 } // release lock
4673
4674 // Wake up poll loop since it may need to make new input dispatching choices.
4675 mLooper->wake();
4676}
4677
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004679 if (DEBUG_FOCUS) {
4680 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682
4683 bool changed;
4684 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004685 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
4687 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4688 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 }
4691
4692 if (mDispatchEnabled && !enabled) {
4693 resetAndDropEverythingLocked("dispatcher is being disabled");
4694 }
4695
4696 mDispatchEnabled = enabled;
4697 mDispatchFrozen = frozen;
4698 changed = true;
4699 } else {
4700 changed = false;
4701 }
4702
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004703 if (DEBUG_FOCUS) {
4704 logDispatchStateLocked();
4705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 } // release lock
4707
4708 if (changed) {
4709 // Wake up poll loop since it may need to make new input dispatching choices.
4710 mLooper->wake();
4711 }
4712}
4713
4714void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004715 if (DEBUG_FOCUS) {
4716 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718
4719 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004720 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721
4722 if (mInputFilterEnabled == enabled) {
4723 return;
4724 }
4725
4726 mInputFilterEnabled = enabled;
4727 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4728 } // release lock
4729
4730 // Wake up poll loop since there might be work to do to drop everything.
4731 mLooper->wake();
4732}
4733
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004734void InputDispatcher::setInTouchMode(bool inTouchMode) {
4735 std::scoped_lock lock(mLock);
4736 mInTouchMode = inTouchMode;
4737}
4738
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004739void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4740 if (opacity < 0 || opacity > 1) {
4741 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4742 return;
4743 }
4744
4745 std::scoped_lock lock(mLock);
4746 mMaximumObscuringOpacityForTouch = opacity;
4747}
4748
4749void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4750 std::scoped_lock lock(mLock);
4751 mBlockUntrustedTouchesMode = mode;
4752}
4753
arthurhungb89ccb02020-12-30 16:19:01 +08004754bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4755 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004756 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004757 if (DEBUG_FOCUS) {
4758 ALOGD("Trivial transfer to same window.");
4759 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004760 return true;
4761 }
4762
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004764 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765
chaviw98318de2021-05-19 16:45:23 -05004766 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4767 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004768 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004769 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 return false;
4771 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004772 if (DEBUG_FOCUS) {
4773 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4774 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004777 if (DEBUG_FOCUS) {
4778 ALOGD("Cannot transfer focus because windows are on different displays.");
4779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 return false;
4781 }
4782
4783 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004784 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4785 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004786 for (size_t i = 0; i < state.windows.size(); i++) {
4787 const TouchedWindow& touchedWindow = state.windows[i];
4788 if (touchedWindow.windowHandle == fromWindowHandle) {
4789 int32_t oldTargetFlags = touchedWindow.targetFlags;
4790 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004792 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 int32_t newTargetFlags = oldTargetFlags &
4795 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4796 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004797 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798
arthurhungb89ccb02020-12-30 16:19:01 +08004799 // Store the dragging window.
4800 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004801 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004802 }
4803
Jeff Brownf086ddb2014-02-11 14:28:48 -08004804 found = true;
4805 goto Found;
4806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 }
4808 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004811 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004812 if (DEBUG_FOCUS) {
4813 ALOGD("Focus transfer failed because from window did not have focus.");
4814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 return false;
4816 }
4817
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004818 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4819 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004820 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004821 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 CancelationOptions
4823 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4824 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004826 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
4828
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004829 if (DEBUG_FOCUS) {
4830 logDispatchStateLocked();
4831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 } // release lock
4833
4834 // Wake up poll loop since it may need to make new input dispatching choices.
4835 mLooper->wake();
4836 return true;
4837}
4838
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004839// Binder call
4840bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4841 sp<IBinder> fromToken;
4842 { // acquire lock
4843 std::scoped_lock _l(mLock);
4844
chaviw98318de2021-05-19 16:45:23 -05004845 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004846 if (toWindowHandle == nullptr) {
4847 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4848 return false;
4849 }
4850
4851 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4852
4853 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4854 if (touchStateIt == mTouchStatesByDisplay.end()) {
4855 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4856 displayId);
4857 return false;
4858 }
4859
4860 TouchState& state = touchStateIt->second;
4861 if (state.windows.size() != 1) {
4862 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4863 state.windows.size());
4864 return false;
4865 }
4866 const TouchedWindow& touchedWindow = state.windows[0];
4867 fromToken = touchedWindow.windowHandle->getToken();
4868 } // release lock
4869
4870 return transferTouchFocus(fromToken, destChannelToken);
4871}
4872
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004874 if (DEBUG_FOCUS) {
4875 ALOGD("Resetting and dropping all events (%s).", reason);
4876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877
4878 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4879 synthesizeCancelationEventsForAllConnectionsLocked(options);
4880
4881 resetKeyRepeatLocked();
4882 releasePendingEventLocked();
4883 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004886 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004887 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004889 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890}
4891
4892void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004893 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 dumpDispatchStateLocked(dump);
4895
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004896 std::istringstream stream(dump);
4897 std::string line;
4898
4899 while (std::getline(stream, line, '\n')) {
4900 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902}
4903
Prabir Pradhan99987712020-11-10 18:43:05 -08004904std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4905 std::string dump;
4906
4907 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4908 toString(mFocusedWindowRequestedPointerCapture));
4909
4910 std::string windowName = "None";
4911 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05004912 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004913 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4914 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4915 : "token has capture without window";
4916 }
4917 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4918
4919 return dump;
4920}
4921
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004922void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004923 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4924 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4925 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004926 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927
Tiger Huang721e26f2018-07-24 22:26:19 +08004928 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4929 dump += StringPrintf(INDENT "FocusedApplications:\n");
4930 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4931 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004932 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004933 const std::chrono::duration timeout =
4934 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004935 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004936 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004937 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004940 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004942
Vishnu Nairc519ff72021-01-21 08:23:08 -08004943 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004944 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004946 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004947 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004948 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4949 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004950 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 state.displayId, toString(state.down), toString(state.split),
4952 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004953 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004954 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004955 for (size_t i = 0; i < state.windows.size(); i++) {
4956 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004957 dump += StringPrintf(INDENT4
4958 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4959 i, touchedWindow.windowHandle->getName().c_str(),
4960 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004961 }
4962 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004963 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965 }
4966 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004967 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 }
4969
arthurhung6d4bed92021-03-17 11:59:33 +08004970 if (mDragState) {
4971 dump += StringPrintf(INDENT "DragState:\n");
4972 mDragState->dump(dump, INDENT2);
4973 }
4974
Arthur Hungb92218b2018-08-14 12:00:21 +08004975 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004976 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004977 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004978 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004979 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004980 dump += INDENT2 "Windows:\n";
4981 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05004982 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
4983 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004985 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004986 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004987 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004988 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004990 "applicationInfo.name=%s, "
4991 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004992 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004993 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004994 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004995 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004996 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004997 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004998 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004999 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005000 windowInfo->frameLeft, windowInfo->frameTop,
5001 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005002 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005003 windowInfo->applicationInfo.name.c_str(),
5004 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005005 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005006 dump += StringPrintf(", inputFeatures=%s",
5007 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005008 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005009 "ms, trustedOverlay=%s, hasToken=%s, "
5010 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005011 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005012 millis(windowInfo->dispatchingTimeout),
5013 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005014 toString(windowInfo->token != nullptr),
5015 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005016 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005017 }
5018 } else {
5019 dump += INDENT2 "Windows: <none>\n";
5020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 }
5022 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005023 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 }
5025
Michael Wright3dd60e22019-03-27 22:06:44 +00005026 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005027 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005028 const std::vector<Monitor>& monitors = it.second;
5029 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5030 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005031 }
5032 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005033 const std::vector<Monitor>& monitors = it.second;
5034 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5035 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005038 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 }
5040
5041 nsecs_t currentTime = now();
5042
5043 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005044 if (!mRecentQueue.empty()) {
5045 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005046 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005047 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005048 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005049 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 }
5051 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005052 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 }
5054
5055 // Dump event currently being dispatched.
5056 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005057 dump += INDENT "PendingEvent:\n";
5058 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005059 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005060 dump += StringPrintf(", age=%" PRId64 "ms\n",
5061 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005063 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 }
5065
5066 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005067 if (!mInboundQueue.empty()) {
5068 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005069 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005070 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005071 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005072 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 }
5074 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005075 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 }
5077
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005078 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005079 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005080 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5081 const KeyReplacement& replacement = pair.first;
5082 int32_t newKeyCode = pair.second;
5083 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005084 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005085 }
5086 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005087 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005088 }
5089
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005090 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005091 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005092 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005093 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005095 connection->inputChannel->getFd().get(),
5096 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005097 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005098 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005100 if (!connection->outboundQueue.empty()) {
5101 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5102 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005103 dump += dumpQueue(connection->outboundQueue, currentTime);
5104
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 }
5108
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005109 if (!connection->waitQueue.empty()) {
5110 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5111 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005112 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005114 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 }
5116 }
5117 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005118 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 }
5120
5121 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005122 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5123 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005125 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 }
5127
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005128 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005129 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5130 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5131 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005132 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005133 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134}
5135
Michael Wright3dd60e22019-03-27 22:06:44 +00005136void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5137 const size_t numMonitors = monitors.size();
5138 for (size_t i = 0; i < numMonitors; i++) {
5139 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005140 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005141 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5142 dump += "\n";
5143 }
5144}
5145
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005146class LooperEventCallback : public LooperCallback {
5147public:
5148 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5149 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5150
5151private:
5152 std::function<int(int events)> mCallback;
5153};
5154
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005155Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005156#if DEBUG_CHANNEL_CREATION
5157 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158#endif
5159
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005160 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005161 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005162 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005163
5164 if (result) {
5165 return base::Error(result) << "Failed to open input channel pair with name " << name;
5166 }
5167
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005169 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005170 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005171 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005172 sp<Connection> connection =
5173 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005175 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5176 ALOGE("Created a new connection, but the token %p is already known", token.get());
5177 }
5178 mConnectionsByToken.emplace(token, connection);
5179
5180 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5181 this, std::placeholders::_1, token);
5182
5183 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 } // release lock
5185
5186 // Wake the looper because some connections have changed.
5187 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005188 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189}
5190
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005191Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5192 bool isGestureMonitor,
5193 const std::string& name,
5194 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005195 std::shared_ptr<InputChannel> serverChannel;
5196 std::unique_ptr<InputChannel> clientChannel;
5197 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5198 if (result) {
5199 return base::Error(result) << "Failed to open input channel pair with name " << name;
5200 }
5201
Michael Wright3dd60e22019-03-27 22:06:44 +00005202 { // acquire lock
5203 std::scoped_lock _l(mLock);
5204
5205 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005206 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5207 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005208 }
5209
Garfield Tan15601662020-09-22 15:32:38 -07005210 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005211 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005212 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005213
5214 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5215 ALOGE("Created a new connection, but the token %p is already known", token.get());
5216 }
5217 mConnectionsByToken.emplace(token, connection);
5218 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5219 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005221 auto& monitorsByDisplay =
5222 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005223 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005224
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005225 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005226 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5227 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005228 }
Garfield Tan15601662020-09-22 15:32:38 -07005229
Michael Wright3dd60e22019-03-27 22:06:44 +00005230 // Wake the looper because some connections have changed.
5231 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005232 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005233}
5234
Garfield Tan15601662020-09-22 15:32:38 -07005235status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005237 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238
Garfield Tan15601662020-09-22 15:32:38 -07005239 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240 if (status) {
5241 return status;
5242 }
5243 } // release lock
5244
5245 // Wake the poll loop because removing the connection may have changed the current
5246 // synchronization state.
5247 mLooper->wake();
5248 return OK;
5249}
5250
Garfield Tan15601662020-09-22 15:32:38 -07005251status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5252 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005253 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005254 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005255 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 return BAD_VALUE;
5257 }
5258
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005259 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005260
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005262 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 }
5264
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005265 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266
5267 nsecs_t currentTime = now();
5268 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5269
5270 connection->status = Connection::STATUS_ZOMBIE;
5271 return OK;
5272}
5273
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005274void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5275 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5276 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005277}
5278
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005279void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005280 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005281 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005282 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005283 std::vector<Monitor>& monitors = it->second;
5284 const size_t numMonitors = monitors.size();
5285 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005286 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005287 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5288 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005289 monitors.erase(monitors.begin() + i);
5290 break;
5291 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005292 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005293 if (monitors.empty()) {
5294 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005295 } else {
5296 ++it;
5297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 }
5299}
5300
Michael Wright3dd60e22019-03-27 22:06:44 +00005301status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5302 { // acquire lock
5303 std::scoped_lock _l(mLock);
5304 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5305
5306 if (!foundDisplayId) {
5307 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5308 return BAD_VALUE;
5309 }
5310 int32_t displayId = foundDisplayId.value();
5311
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005312 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5313 mTouchStatesByDisplay.find(displayId);
5314 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005315 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5316 return BAD_VALUE;
5317 }
5318
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005319 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005320 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005321 std::optional<int32_t> foundDeviceId;
5322 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005323 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005324 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005325 foundDeviceId = state.deviceId;
5326 }
5327 }
5328 if (!foundDeviceId || !state.down) {
5329 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005330 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005331 return BAD_VALUE;
5332 }
5333 int32_t deviceId = foundDeviceId.value();
5334
5335 // Send cancel events to all the input channels we're stealing from.
5336 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005337 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005338 options.deviceId = deviceId;
5339 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005340 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005341 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005342 std::shared_ptr<InputChannel> channel =
5343 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005344 if (channel != nullptr) {
5345 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005346 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005347 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005348 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005349 canceledWindows += "]";
5350 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5351 canceledWindows.c_str());
5352
Michael Wright3dd60e22019-03-27 22:06:44 +00005353 // Then clear the current touch state so we stop dispatching to them as well.
5354 state.filterNonMonitors();
5355 }
5356 return OK;
5357}
5358
Prabir Pradhan99987712020-11-10 18:43:05 -08005359void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5360 { // acquire lock
5361 std::scoped_lock _l(mLock);
5362 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005363 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005364 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5365 windowHandle != nullptr ? windowHandle->getName().c_str()
5366 : "token without window");
5367 }
5368
Vishnu Nairc519ff72021-01-21 08:23:08 -08005369 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005370 if (focusedToken != windowToken) {
5371 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5372 enabled ? "enable" : "disable");
5373 return;
5374 }
5375
5376 if (enabled == mFocusedWindowRequestedPointerCapture) {
5377 ALOGW("Ignoring request to %s Pointer Capture: "
5378 "window has %s requested pointer capture.",
5379 enabled ? "enable" : "disable", enabled ? "already" : "not");
5380 return;
5381 }
5382
5383 mFocusedWindowRequestedPointerCapture = enabled;
5384 setPointerCaptureLocked(enabled);
5385 } // release lock
5386
5387 // Wake the thread to process command entries.
5388 mLooper->wake();
5389}
5390
Michael Wright3dd60e22019-03-27 22:06:44 +00005391std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5392 const sp<IBinder>& token) {
5393 for (const auto& it : mGestureMonitorsByDisplay) {
5394 const std::vector<Monitor>& monitors = it.second;
5395 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005396 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005397 return it.first;
5398 }
5399 }
5400 }
5401 return std::nullopt;
5402}
5403
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005404std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5405 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5406 if (gesturePid.has_value()) {
5407 return gesturePid;
5408 }
5409 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5410}
5411
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005412sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005413 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005414 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005415 }
5416
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005417 for (const auto& [token, connection] : mConnectionsByToken) {
5418 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005419 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 }
5421 }
Robert Carr4e670e52018-08-15 13:26:12 -07005422
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005423 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424}
5425
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005426std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5427 sp<Connection> connection = getConnectionLocked(connectionToken);
5428 if (connection == nullptr) {
5429 return "<nullptr>";
5430 }
5431 return connection->getInputChannelName();
5432}
5433
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005434void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005435 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005436 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005437}
5438
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005439void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5440 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005441 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005442 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5443 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 commandEntry->connection = connection;
5445 commandEntry->eventTime = currentTime;
5446 commandEntry->seq = seq;
5447 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005448 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005449 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450}
5451
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005452void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5453 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005455 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005457 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5458 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005460 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461}
5462
Vishnu Nairad321cd2020-08-20 16:40:21 -07005463void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5464 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005465 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5466 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005467 commandEntry->oldToken = oldToken;
5468 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005469 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005470}
5471
arthurhungf452d0b2021-01-06 00:19:52 +08005472void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5473 std::unique_ptr<CommandEntry> commandEntry =
5474 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5475 commandEntry->newToken = token;
5476 commandEntry->x = x;
5477 commandEntry->y = y;
5478 postCommandLocked(std::move(commandEntry));
5479}
5480
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005481void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5482 if (connection == nullptr) {
5483 LOG_ALWAYS_FATAL("Caller must check for nullness");
5484 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005485 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5486 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005487 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005488 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005489 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005490 return;
5491 }
5492 /**
5493 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5494 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5495 * has changed. This could cause newer entries to time out before the already dispatched
5496 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5497 * processes the events linearly. So providing information about the oldest entry seems to be
5498 * most useful.
5499 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005500 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005501 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5502 std::string reason =
5503 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005504 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005505 ns2ms(currentWait),
5506 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005507 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005508 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005509
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005510 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5511
5512 // Stop waking up for events on this connection, it is already unresponsive
5513 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005514}
5515
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005516void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5517 std::string reason =
5518 StringPrintf("%s does not have a focused window", application->getName().c_str());
5519 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005520
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005521 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5522 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5523 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005524 postCommandLocked(std::move(commandEntry));
5525}
5526
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005527void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5528 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5529 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5530 commandEntry->obscuringPackage = obscuringPackage;
5531 postCommandLocked(std::move(commandEntry));
5532}
5533
chaviw98318de2021-05-19 16:45:23 -05005534void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005535 const std::string& reason) {
5536 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5537 updateLastAnrStateLocked(windowLabel, reason);
5538}
5539
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005540void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5541 const std::string& reason) {
5542 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005543 updateLastAnrStateLocked(windowLabel, reason);
5544}
5545
5546void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5547 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005549 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 struct tm tm;
5551 localtime_r(&t, &tm);
5552 char timestr[64];
5553 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005554 mLastAnrState.clear();
5555 mLastAnrState += INDENT "ANR:\n";
5556 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005557 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5558 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005559 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560}
5561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005562void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 mLock.unlock();
5564
5565 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5566
5567 mLock.lock();
5568}
5569
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005570void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 sp<Connection> connection = commandEntry->connection;
5572
5573 if (connection->status != Connection::STATUS_ZOMBIE) {
5574 mLock.unlock();
5575
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005576 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577
5578 mLock.lock();
5579 }
5580}
5581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005582void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005583 sp<IBinder> oldToken = commandEntry->oldToken;
5584 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005585 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005586 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005587 mLock.lock();
5588}
5589
arthurhungf452d0b2021-01-06 00:19:52 +08005590void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5591 sp<IBinder> newToken = commandEntry->newToken;
5592 mLock.unlock();
5593 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5594 mLock.lock();
5595}
5596
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005597void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005599
5600 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5601
5602 mLock.lock();
5603}
5604
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005605void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005606 mLock.unlock();
5607
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005608 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609
5610 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005611}
5612
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005613void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005614 mLock.unlock();
5615
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005616 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5617
5618 mLock.lock();
5619}
5620
5621void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5622 mLock.unlock();
5623
5624 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5625
5626 mLock.lock();
5627}
5628
5629void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5630 mLock.unlock();
5631
5632 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005633
5634 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005635}
5636
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005637void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5638 mLock.unlock();
5639
5640 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5641
5642 mLock.lock();
5643}
5644
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5646 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005647 KeyEntry& entry = *(commandEntry->keyEntry);
5648 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649
5650 mLock.unlock();
5651
Michael Wright2b3c3302018-03-02 17:19:13 +00005652 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005653 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005654 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005655 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5656 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005657 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659
5660 mLock.lock();
5661
5662 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005663 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005665 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005667 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5668 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670}
5671
chaviwfd6d3512019-03-25 13:23:49 -07005672void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5673 mLock.unlock();
5674 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5675 mLock.lock();
5676}
5677
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005678/**
5679 * Connection is responsive if it has no events in the waitQueue that are older than the
5680 * current time.
5681 */
5682static bool isConnectionResponsive(const Connection& connection) {
5683 const nsecs_t currentTime = now();
5684 for (const DispatchEntry* entry : connection.waitQueue) {
5685 if (entry->timeoutTime < currentTime) {
5686 return false;
5687 }
5688 }
5689 return true;
5690}
5691
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005692void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005694 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005696 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005697
5698 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005699 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005700 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005701 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005703 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005704 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005705 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005706 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5707 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005708 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005709 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5710 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5711 connection->inputChannel->getConnectionToken(),
5712 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5713 finishTime);
5714 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005715
5716 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005717 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005718 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005719 restartEvent =
5720 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005721 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005722 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005723 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5724 handled);
5725 } else {
5726 restartEvent = false;
5727 }
5728
5729 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005730 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005731 // contents of the wait queue to have been drained, so we need to double-check
5732 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005733 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5734 if (dispatchEntryIt != connection->waitQueue.end()) {
5735 dispatchEntry = *dispatchEntryIt;
5736 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005737 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5738 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005739 if (!connection->responsive) {
5740 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005741 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005742 // The connection was unresponsive, and now it's responsive.
5743 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005744 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005745 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005746 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005747 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005748 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005749 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005750 } else {
5751 releaseDispatchEntry(dispatchEntry);
5752 }
5753 }
5754
5755 // Start the next dispatch cycle for this connection.
5756 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757}
5758
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005759void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5760 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5761 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5762 monitorUnresponsiveCommand->pid = pid;
5763 monitorUnresponsiveCommand->reason = std::move(reason);
5764 postCommandLocked(std::move(monitorUnresponsiveCommand));
5765}
5766
5767void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5768 std::string reason) {
5769 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5770 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5771 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5772 windowUnresponsiveCommand->reason = std::move(reason);
5773 postCommandLocked(std::move(windowUnresponsiveCommand));
5774}
5775
5776void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5777 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5778 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5779 monitorResponsiveCommand->pid = pid;
5780 postCommandLocked(std::move(monitorResponsiveCommand));
5781}
5782
5783void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5784 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5785 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5786 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5787 postCommandLocked(std::move(windowResponsiveCommand));
5788}
5789
5790/**
5791 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5792 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5793 * command entry to the command queue.
5794 */
5795void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5796 std::string reason) {
5797 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5798 if (connection.monitor) {
5799 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5800 reason.c_str());
5801 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5802 if (!pid.has_value()) {
5803 ALOGE("Could not find unresponsive monitor for connection %s",
5804 connection.inputChannel->getName().c_str());
5805 return;
5806 }
5807 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5808 return;
5809 }
5810 // If not a monitor, must be a window
5811 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5812 reason.c_str());
5813 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5814}
5815
5816/**
5817 * Tell the policy that a connection has become responsive so that it can stop ANR.
5818 */
5819void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5820 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5821 if (connection.monitor) {
5822 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5823 if (!pid.has_value()) {
5824 ALOGE("Could not find responsive monitor for connection %s",
5825 connection.inputChannel->getName().c_str());
5826 return;
5827 }
5828 sendMonitorResponsiveCommandLocked(pid.value());
5829 return;
5830 }
5831 // If not a monitor, must be a window
5832 sendWindowResponsiveCommandLocked(connectionToken);
5833}
5834
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005836 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005837 KeyEntry& keyEntry, bool handled) {
5838 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005839 if (!handled) {
5840 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005841 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005842 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005843 return false;
5844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005846 // Get the fallback key state.
5847 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005848 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005849 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005850 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005851 connection->inputState.removeFallbackKey(originalKeyCode);
5852 }
5853
5854 if (handled || !dispatchEntry->hasForegroundTarget()) {
5855 // If the application handles the original key for which we previously
5856 // generated a fallback or if the window is not a foreground window,
5857 // then cancel the associated fallback key, if any.
5858 if (fallbackKeyCode != -1) {
5859 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005861 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005862 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005863 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005865 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005866 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867
5868 mLock.unlock();
5869
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005870 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005871 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872
5873 mLock.lock();
5874
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005875 // Cancel the fallback key.
5876 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005878 "application handled the original non-fallback key "
5879 "or is no longer a foreground target, "
5880 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881 options.keyCode = fallbackKeyCode;
5882 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005884 connection->inputState.removeFallbackKey(originalKeyCode);
5885 }
5886 } else {
5887 // If the application did not handle a non-fallback key, first check
5888 // that we are in a good state to perform unhandled key event processing
5889 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005890 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005891 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005893 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005894 "since this is not an initial down. "
5895 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005896 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005898 return false;
5899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005901 // Dispatch the unhandled key to the policy.
5902#if DEBUG_OUTBOUND_EVENT_DETAILS
5903 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005904 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005905 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005906#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005907 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005908
5909 mLock.unlock();
5910
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005911 bool fallback =
5912 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005913 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005914
5915 mLock.lock();
5916
5917 if (connection->status != Connection::STATUS_NORMAL) {
5918 connection->inputState.removeFallbackKey(originalKeyCode);
5919 return false;
5920 }
5921
5922 // Latch the fallback keycode for this key on an initial down.
5923 // The fallback keycode cannot change at any other point in the lifecycle.
5924 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005926 fallbackKeyCode = event.getKeyCode();
5927 } else {
5928 fallbackKeyCode = AKEYCODE_UNKNOWN;
5929 }
5930 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5931 }
5932
5933 ALOG_ASSERT(fallbackKeyCode != -1);
5934
5935 // Cancel the fallback key if the policy decides not to send it anymore.
5936 // We will continue to dispatch the key to the policy but we will no
5937 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005938 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5939 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940#if DEBUG_OUTBOUND_EVENT_DETAILS
5941 if (fallback) {
5942 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005943 "as a fallback for %d, but on the DOWN it had requested "
5944 "to send %d instead. Fallback canceled.",
5945 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005946 } else {
5947 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005948 "but on the DOWN it had requested to send %d. "
5949 "Fallback canceled.",
5950 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005951 }
5952#endif
5953
5954 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5955 "canceling fallback, policy no longer desires it");
5956 options.keyCode = fallbackKeyCode;
5957 synthesizeCancelationEventsForConnectionLocked(connection, options);
5958
5959 fallback = false;
5960 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005961 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005962 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005963 }
5964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965
5966#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005967 {
5968 std::string msg;
5969 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5970 connection->inputState.getFallbackKeys();
5971 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005972 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005974 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005975 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976 }
5977#endif
5978
5979 if (fallback) {
5980 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005981 keyEntry.eventTime = event.getEventTime();
5982 keyEntry.deviceId = event.getDeviceId();
5983 keyEntry.source = event.getSource();
5984 keyEntry.displayId = event.getDisplayId();
5985 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5986 keyEntry.keyCode = fallbackKeyCode;
5987 keyEntry.scanCode = event.getScanCode();
5988 keyEntry.metaState = event.getMetaState();
5989 keyEntry.repeatCount = event.getRepeatCount();
5990 keyEntry.downTime = event.getDownTime();
5991 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005992
5993#if DEBUG_OUTBOUND_EVENT_DETAILS
5994 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005995 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005996 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005997#endif
5998 return true; // restart the event
5999 } else {
6000#if DEBUG_OUTBOUND_EVENT_DETAILS
6001 ALOGD("Unhandled key event: No fallback key.");
6002#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006003
6004 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006005 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006006 }
6007 }
6008 return false;
6009}
6010
6011bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006012 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006013 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006014 return false;
6015}
6016
6017void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6018 mLock.unlock();
6019
Sean Stoutb4e0a592021-02-23 07:34:53 -08006020 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6021 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022
6023 mLock.lock();
6024}
6025
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026void InputDispatcher::traceInboundQueueLengthLocked() {
6027 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006028 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 }
6030}
6031
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006032void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033 if (ATRACE_ENABLED()) {
6034 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006035 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6036 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037 }
6038}
6039
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006040void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041 if (ATRACE_ENABLED()) {
6042 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006043 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6044 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 }
6046}
6047
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006048void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006049 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006051 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 dumpDispatchStateLocked(dump);
6053
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006054 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006055 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006056 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057 }
6058}
6059
6060void InputDispatcher::monitor() {
6061 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006062 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006064 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065}
6066
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006067/**
6068 * Wake up the dispatcher and wait until it processes all events and commands.
6069 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6070 * this method can be safely called from any thread, as long as you've ensured that
6071 * the work you are interested in completing has already been queued.
6072 */
6073bool InputDispatcher::waitForIdle() {
6074 /**
6075 * Timeout should represent the longest possible time that a device might spend processing
6076 * events and commands.
6077 */
6078 constexpr std::chrono::duration TIMEOUT = 100ms;
6079 std::unique_lock lock(mLock);
6080 mLooper->wake();
6081 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6082 return result == std::cv_status::no_timeout;
6083}
6084
Vishnu Naire798b472020-07-23 13:52:21 -07006085/**
6086 * Sets focus to the window identified by the token. This must be called
6087 * after updating any input window handles.
6088 *
6089 * Params:
6090 * request.token - input channel token used to identify the window that should gain focus.
6091 * request.focusedToken - the token that the caller expects currently to be focused. If the
6092 * specified token does not match the currently focused window, this request will be dropped.
6093 * If the specified focused token matches the currently focused window, the call will succeed.
6094 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6095 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6096 * when requesting the focus change. This determines which request gets
6097 * precedence if there is a focus change request from another source such as pointer down.
6098 */
Vishnu Nair958da932020-08-21 17:12:37 -07006099void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6100 { // acquire lock
6101 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006102 std::optional<FocusResolver::FocusChanges> changes =
6103 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6104 if (changes) {
6105 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006106 }
6107 } // release lock
6108 // Wake up poll loop since it may need to make new input dispatching choices.
6109 mLooper->wake();
6110}
6111
Vishnu Nairc519ff72021-01-21 08:23:08 -08006112void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6113 if (changes.oldFocus) {
6114 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006115 if (focusedInputChannel) {
6116 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6117 "focus left window");
6118 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006119 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006120 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006121 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006122 if (changes.newFocus) {
6123 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006124 }
6125
Prabir Pradhan99987712020-11-10 18:43:05 -08006126 // If a window has pointer capture, then it must have focus. We need to ensure that this
6127 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6128 // If the window loses focus before it loses pointer capture, then the window can be in a state
6129 // where it has pointer capture but not focus, violating the contract. Therefore we must
6130 // dispatch the pointer capture event before the focus event. Since focus events are added to
6131 // the front of the queue (above), we add the pointer capture event to the front of the queue
6132 // after the focus events are added. This ensures the pointer capture event ends up at the
6133 // front.
6134 disablePointerCaptureForcedLocked();
6135
Vishnu Nairc519ff72021-01-21 08:23:08 -08006136 if (mFocusedDisplayId == changes.displayId) {
6137 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006138 }
6139}
Vishnu Nair958da932020-08-21 17:12:37 -07006140
Prabir Pradhan99987712020-11-10 18:43:05 -08006141void InputDispatcher::disablePointerCaptureForcedLocked() {
6142 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6143 return;
6144 }
6145
6146 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6147
6148 if (mFocusedWindowRequestedPointerCapture) {
6149 mFocusedWindowRequestedPointerCapture = false;
6150 setPointerCaptureLocked(false);
6151 }
6152
6153 if (!mWindowTokenWithPointerCapture) {
6154 // No need to send capture changes because no window has capture.
6155 return;
6156 }
6157
6158 if (mPendingEvent != nullptr) {
6159 // Move the pending event to the front of the queue. This will give the chance
6160 // for the pending event to be dropped if it is a captured event.
6161 mInboundQueue.push_front(mPendingEvent);
6162 mPendingEvent = nullptr;
6163 }
6164
6165 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6166 false /* hasCapture */);
6167 mInboundQueue.push_front(std::move(entry));
6168}
6169
Prabir Pradhan99987712020-11-10 18:43:05 -08006170void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6171 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6172 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6173 commandEntry->enabled = enabled;
6174 postCommandLocked(std::move(commandEntry));
6175}
6176
6177void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6178 android::inputdispatcher::CommandEntry* commandEntry) {
6179 mLock.unlock();
6180
6181 mPolicy->setPointerCapture(commandEntry->enabled);
6182
6183 mLock.lock();
6184}
6185
Vishnu Nair599f1412021-06-21 10:39:58 -07006186void InputDispatcher::displayRemoved(int32_t displayId) {
6187 { // acquire lock
6188 std::scoped_lock _l(mLock);
6189 // Set an empty list to remove all handles from the specific display.
6190 setInputWindowsLocked(/* window handles */ {}, displayId);
6191 setFocusedApplicationLocked(displayId, nullptr);
6192 // Call focus resolver to clean up stale requests. This must be called after input windows
6193 // have been removed for the removed display.
6194 mFocusResolver.displayRemoved(displayId);
6195 } // release lock
6196
6197 // Wake up poll loop since it may need to make new input dispatching choices.
6198 mLooper->wake();
6199}
6200
Garfield Tane84e6f92019-08-29 17:28:41 -07006201} // namespace android::inputdispatcher