blob: 6e9430a975619d0e780738da79591518d5457781 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080052#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050053#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070054#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100055#include <binder/IServiceManager.h>
56#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080057#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <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;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100085using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080086using android::os::InputEventInjectionResult;
87using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100088using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080089
Garfield Tane84e6f92019-08-29 17:28:41 -070090namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Prabir Pradhan93a0f912021-04-21 13:47:42 -070092// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
93// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
94static bool isPerWindowInputRotationEnabled() {
95 static const bool PER_WINDOW_INPUT_ROTATION =
96 base::GetBoolProperty("persist.debug.per_window_input_rotation", false);
97 return PER_WINDOW_INPUT_ROTATION;
98}
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100// Default input dispatching timeout if there is no focused application or paused window
101// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800102const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
103 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
104 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105
106// Amount of time to allow for all pending events to be processed when an app switch
107// key is on the way. This is used to preempt input dispatch and drop input events
108// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
111// Amount of time to allow for an event to be dispatched (measured since its eventTime)
112// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000113constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// 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 +0000116constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
117
118// Log a warning when an interception call takes longer than this to process.
119constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700121// Additional key latency in case a connection is still processing some motion events.
122// This will help with the case when a user touched a button that opens a new window,
123// and gives us the chance to dispatch the key to this new window.
124constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000127constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
128
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000129// Event log tags. See EventLogTags.logtags for reference
130constexpr int LOGTAG_INPUT_INTERACTION = 62000;
131constexpr int LOGTAG_INPUT_FOCUS = 62001;
132
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133static inline nsecs_t now() {
134 return systemTime(SYSTEM_TIME_MONOTONIC);
135}
136
137static inline const char* toString(bool value) {
138 return value ? "true" : "false";
139}
140
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000141static inline const std::string toString(sp<IBinder> binder) {
142 if (binder == nullptr) {
143 return "<null>";
144 }
145 return StringPrintf("%p", binder.get());
146}
147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
150 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151}
152
153static bool isValidKeyAction(int32_t action) {
154 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AKEY_EVENT_ACTION_DOWN:
156 case AKEY_EVENT_ACTION_UP:
157 return true;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
163static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 ALOGE("Key event has invalid action code 0x%x", action);
166 return false;
167 }
168 return true;
169}
170
Michael Wright7b159c92015-05-14 14:48:03 +0100171static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_DOWN:
174 case AMOTION_EVENT_ACTION_UP:
175 case AMOTION_EVENT_ACTION_CANCEL:
176 case AMOTION_EVENT_ACTION_MOVE:
177 case AMOTION_EVENT_ACTION_OUTSIDE:
178 case AMOTION_EVENT_ACTION_HOVER_ENTER:
179 case AMOTION_EVENT_ACTION_HOVER_MOVE:
180 case AMOTION_EVENT_ACTION_HOVER_EXIT:
181 case AMOTION_EVENT_ACTION_SCROLL:
182 return true;
183 case AMOTION_EVENT_ACTION_POINTER_DOWN:
184 case AMOTION_EVENT_ACTION_POINTER_UP: {
185 int32_t index = getMotionEventActionPointerIndex(action);
186 return index >= 0 && index < pointerCount;
187 }
188 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
189 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
190 return actionButton != 0;
191 default:
192 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 }
194}
195
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500196static int64_t millis(std::chrono::nanoseconds t) {
197 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
198}
199
Michael Wright7b159c92015-05-14 14:48:03 +0100200static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700201 const PointerProperties* pointerProperties) {
202 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 ALOGE("Motion event has invalid action code 0x%x", action);
204 return false;
205 }
206 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000207 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700208 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 return false;
210 }
211 BitSet32 pointerIdBits;
212 for (size_t i = 0; i < pointerCount; i++) {
213 int32_t id = pointerProperties[i].id;
214 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700215 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
216 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 return false;
218 }
219 if (pointerIdBits.hasBit(id)) {
220 ALOGE("Motion event has duplicate pointer id %d", id);
221 return false;
222 }
223 pointerIdBits.markBit(id);
224 }
225 return true;
226}
227
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000230 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
232
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000233 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 bool first = true;
235 Region::const_iterator cur = region.begin();
236 Region::const_iterator const tail = region.end();
237 while (cur != tail) {
238 if (first) {
239 first = false;
240 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800241 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800243 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 cur++;
245 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000246 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247}
248
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500249static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
250 constexpr size_t maxEntries = 50; // max events to print
251 constexpr size_t skipBegin = maxEntries / 2;
252 const size_t skipEnd = queue.size() - maxEntries / 2;
253 // skip from maxEntries / 2 ... size() - maxEntries/2
254 // only print from 0 .. skipBegin and then from skipEnd .. size()
255
256 std::string dump;
257 for (size_t i = 0; i < queue.size(); i++) {
258 const DispatchEntry& entry = *queue[i];
259 if (i >= skipBegin && i < skipEnd) {
260 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
261 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
262 continue;
263 }
264 dump.append(INDENT4);
265 dump += entry.eventEntry->getDescription();
266 dump += StringPrintf(", seq=%" PRIu32
267 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
268 entry.seq, entry.targetFlags, entry.resolvedAction,
269 ns2ms(currentTime - entry.eventEntry->eventTime));
270 if (entry.deliveryTime != 0) {
271 // This entry was delivered, so add information on how long we've been waiting
272 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
273 }
274 dump.append("\n");
275 }
276 return dump;
277}
278
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700279/**
280 * Find the entry in std::unordered_map by key, and return it.
281 * If the entry is not found, return a default constructed entry.
282 *
283 * Useful when the entries are vectors, since an empty vector will be returned
284 * if the entry is not found.
285 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
286 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700287template <typename K, typename V>
288static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700289 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700290 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800291}
292
chaviwaf87b3e2019-10-01 16:59:28 -0700293static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
294 if (first == second) {
295 return true;
296 }
297
298 if (first == nullptr || second == nullptr) {
299 return false;
300 }
301
302 return first->getToken() == second->getToken();
303}
304
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000305static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
306 if (first == nullptr || second == nullptr) {
307 return false;
308 }
309 return first->applicationInfo.token != nullptr &&
310 first->applicationInfo.token == second->applicationInfo.token;
311}
312
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800313static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
314 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
315}
316
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700318 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900320 if (eventEntry->type == EventEntry::Type::MOTION) {
321 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800322 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900323 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800324 // Use identity transform for events that are not pointer events because their axes
325 // values do not represent on-screen coordinates, so they should not have any window
326 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900327 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700328 1.0f /*globalScaleFactor*/,
329 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900330 }
331 }
332
chaviw1ff3d1e2020-07-01 15:53:47 -0700333 if (inputTarget.useDefaultPointerTransform()) {
334 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700335 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700336 inputTarget.globalScaleFactor,
337 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 }
339
340 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
341 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700343 std::vector<PointerCoords> pointerCoords;
344 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 // Use the first pointer information to normalize all other pointers. This could be any pointer
347 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700348 // uses the transform for the normalized pointer.
349 const ui::Transform& firstPointerTransform =
350 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
351 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352
353 // Iterate through all pointers in the event to normalize against the first.
354 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
355 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
356 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358
359 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700360 // First, apply the current pointer's transform to update the coordinates into
361 // window space.
362 pointerCoords[pointerIndex].transform(currTransform);
363 // Next, apply the inverse transform of the normalized coordinates so the
364 // current coordinates are transformed into the normalized coordinate space.
365 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366 }
367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700368 std::unique_ptr<MotionEntry> combinedMotionEntry =
369 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
370 motionEntry.deviceId, motionEntry.source,
371 motionEntry.displayId, motionEntry.policyFlags,
372 motionEntry.action, motionEntry.actionButton,
373 motionEntry.flags, motionEntry.metaState,
374 motionEntry.buttonState, motionEntry.classification,
375 motionEntry.edgeFlags, motionEntry.xPrecision,
376 motionEntry.yPrecision, motionEntry.xCursorPosition,
377 motionEntry.yCursorPosition, motionEntry.downTime,
378 motionEntry.pointerCount, motionEntry.pointerProperties,
379 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 if (motionEntry.injectionState) {
382 combinedMotionEntry->injectionState = motionEntry.injectionState;
383 combinedMotionEntry->injectionState->refCount += 1;
384 }
385
386 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700387 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700388 firstPointerTransform, inputTarget.globalScaleFactor,
389 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 return dispatchEntry;
391}
392
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700393static void addGestureMonitors(const std::vector<Monitor>& monitors,
394 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
395 float yOffset = 0) {
396 if (monitors.empty()) {
397 return;
398 }
399 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
400 for (const Monitor& monitor : monitors) {
401 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
402 }
403}
404
Garfield Tan15601662020-09-22 15:32:38 -0700405static status_t openInputChannelPair(const std::string& name,
406 std::shared_ptr<InputChannel>& serverChannel,
407 std::unique_ptr<InputChannel>& clientChannel) {
408 std::unique_ptr<InputChannel> uniqueServerChannel;
409 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
410
411 serverChannel = std::move(uniqueServerChannel);
412 return result;
413}
414
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500415template <typename T>
416static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
417 if (lhs == nullptr && rhs == nullptr) {
418 return true;
419 }
420 if (lhs == nullptr || rhs == nullptr) {
421 return false;
422 }
423 return *lhs == *rhs;
424}
425
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000426static sp<IPlatformCompatNative> getCompatService() {
427 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
428 if (service == nullptr) {
429 ALOGE("Failed to link to compat service");
430 return nullptr;
431 }
432 return interface_cast<IPlatformCompatNative>(service);
433}
434
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000435static KeyEvent createKeyEvent(const KeyEntry& entry) {
436 KeyEvent event;
437 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
438 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
439 entry.repeatCount, entry.downTime, entry.eventTime);
440 return event;
441}
442
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000443static std::optional<int32_t> findMonitorPidByToken(
444 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
445 const sp<IBinder>& token) {
446 for (const auto& it : monitorsByDisplay) {
447 const std::vector<Monitor>& monitors = it.second;
448 for (const Monitor& monitor : monitors) {
449 if (monitor.inputChannel->getConnectionToken() == token) {
450 return monitor.pid;
451 }
452 }
453 }
454 return std::nullopt;
455}
456
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000457static bool shouldReportMetricsForConnection(const Connection& connection) {
458 // Do not keep track of gesture monitors. They receive every event and would disproportionately
459 // affect the statistics.
460 if (connection.monitor) {
461 return false;
462 }
463 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
464 if (!connection.responsive) {
465 return false;
466 }
467 return true;
468}
469
470static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
471 const Connection& connection) {
472 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
473 const int32_t& inputEventId = eventEntry.id;
474 if (inputEventId != dispatchEntry.resolvedEventId) {
475 // Event was transmuted
476 return false;
477 }
478 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
479 return false;
480 }
481 // Only track latency for events that originated from hardware
482 if (eventEntry.isSynthesized()) {
483 return false;
484 }
485 const EventEntry::Type& inputEventEntryType = eventEntry.type;
486 if (inputEventEntryType == EventEntry::Type::KEY) {
487 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
488 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
489 return false;
490 }
491 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
492 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
493 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
494 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
495 return false;
496 }
497 } else {
498 // Not a key or a motion
499 return false;
500 }
501 if (!shouldReportMetricsForConnection(connection)) {
502 return false;
503 }
504 return true;
505}
506
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507// --- InputDispatcher ---
508
Garfield Tan00f511d2019-06-12 16:55:40 -0700509InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
510 : mPolicy(policy),
511 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700512 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800513 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700514 mAppSwitchSawKeyDown(false),
515 mAppSwitchDueTime(LONG_LONG_MAX),
516 mNextUnblockedEvent(nullptr),
517 mDispatchEnabled(false),
518 mDispatchFrozen(false),
519 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800520 // mInTouchMode will be initialized by the WindowManager to the default device config.
521 // To avoid leaking stack in case that call never comes, and for tests,
522 // initialize it here anyways.
523 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100524 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000525 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800526 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000527 mLatencyAggregator(),
528 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000529 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800531 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532
Yi Kong9b14ac62018-07-17 13:48:38 -0700533 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 policy->getDispatcherConfiguration(&mConfig);
536}
537
538InputDispatcher::~InputDispatcher() {
539 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800540 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541
542 resetKeyRepeatLocked();
543 releasePendingEventLocked();
544 drainInboundQueueLocked();
545 }
546
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000547 while (!mConnectionsByToken.empty()) {
548 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700549 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 }
551}
552
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700553status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700554 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700555 return ALREADY_EXISTS;
556 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700557 mThread = std::make_unique<InputThread>(
558 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
559 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700560}
561
562status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700563 if (mThread && mThread->isCallingThread()) {
564 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700565 return INVALID_OPERATION;
566 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700567 mThread.reset();
568 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700569}
570
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571void InputDispatcher::dispatchOnce() {
572 nsecs_t nextWakeupTime = LONG_LONG_MAX;
573 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800574 std::scoped_lock _l(mLock);
575 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
577 // Run a dispatch loop if there are no pending commands.
578 // The dispatch loop might enqueue commands to run afterwards.
579 if (!haveCommandsLocked()) {
580 dispatchOnceInnerLocked(&nextWakeupTime);
581 }
582
583 // Run all pending commands if there are any.
584 // If any commands were run then force the next poll to wake up immediately.
585 if (runCommandsLockedInterruptible()) {
586 nextWakeupTime = LONG_LONG_MIN;
587 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800588
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700589 // If we are still waiting for ack on some events,
590 // we might have to wake up earlier to check if an app is anr'ing.
591 const nsecs_t nextAnrCheck = processAnrsLocked();
592 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
593
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800594 // We are about to enter an infinitely long sleep, because we have no commands or
595 // pending or queued events
596 if (nextWakeupTime == LONG_LONG_MAX) {
597 mDispatcherEnteredIdle.notify_all();
598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 } // release lock
600
601 // Wait for callback or timeout or wake. (make sure we round up, not down)
602 nsecs_t currentTime = now();
603 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
604 mLooper->pollOnce(timeoutMillis);
605}
606
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700607/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500608 * Raise ANR if there is no focused window.
609 * Before the ANR is raised, do a final state check:
610 * 1. The currently focused application must be the same one we are waiting for.
611 * 2. Ensure we still don't have a focused window.
612 */
613void InputDispatcher::processNoFocusedWindowAnrLocked() {
614 // Check if the application that we are waiting for is still focused.
615 std::shared_ptr<InputApplicationHandle> focusedApplication =
616 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
617 if (focusedApplication == nullptr ||
618 focusedApplication->getApplicationToken() !=
619 mAwaitedFocusedApplication->getApplicationToken()) {
620 // Unexpected because we should have reset the ANR timer when focused application changed
621 ALOGE("Waited for a focused window, but focused application has already changed to %s",
622 focusedApplication->getName().c_str());
623 return; // The focused application has changed.
624 }
625
626 const sp<InputWindowHandle>& focusedWindowHandle =
627 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
628 if (focusedWindowHandle != nullptr) {
629 return; // We now have a focused window. No need for ANR.
630 }
631 onAnrLocked(mAwaitedFocusedApplication);
632}
633
634/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700635 * Check if any of the connections' wait queues have events that are too old.
636 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
637 * Return the time at which we should wake up next.
638 */
639nsecs_t InputDispatcher::processAnrsLocked() {
640 const nsecs_t currentTime = now();
641 nsecs_t nextAnrCheck = LONG_LONG_MAX;
642 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
643 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
644 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500645 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700646 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500647 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700648 return LONG_LONG_MIN;
649 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500650 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700651 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
652 }
653 }
654
655 // Check if any connection ANRs are due
656 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
657 if (currentTime < nextAnrCheck) { // most likely scenario
658 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
659 }
660
661 // If we reached here, we have an unresponsive connection.
662 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
663 if (connection == nullptr) {
664 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
665 return nextAnrCheck;
666 }
667 connection->responsive = false;
668 // Stop waking up for this unresponsive connection
669 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000670 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671 return LONG_LONG_MIN;
672}
673
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500674std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700675 sp<InputWindowHandle> window = getWindowHandleLocked(token);
676 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500677 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500679 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700680}
681
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
683 nsecs_t currentTime = now();
684
Jeff Browndc5992e2014-04-11 01:27:26 -0700685 // Reset the key repeat timer whenever normal dispatch is suspended while the
686 // device is in a non-interactive state. This is to ensure that we abort a key
687 // repeat if the device is just coming out of sleep.
688 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 resetKeyRepeatLocked();
690 }
691
692 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
693 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100694 if (DEBUG_FOCUS) {
695 ALOGD("Dispatch frozen. Waiting some more.");
696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 return;
698 }
699
700 // Optimize latency of app switches.
701 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
702 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
703 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
704 if (mAppSwitchDueTime < *nextWakeupTime) {
705 *nextWakeupTime = mAppSwitchDueTime;
706 }
707
708 // Ready to start a new event.
709 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700711 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 if (isAppSwitchDue) {
713 // The inbound queue is empty so the app switch key we were waiting
714 // for will never arrive. Stop waiting for it.
715 resetPendingAppSwitchLocked(false);
716 isAppSwitchDue = false;
717 }
718
719 // Synthesize a key repeat if appropriate.
720 if (mKeyRepeatState.lastKeyEntry) {
721 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
722 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
723 } else {
724 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
725 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
726 }
727 }
728 }
729
730 // Nothing to do if there is no pending event.
731 if (!mPendingEvent) {
732 return;
733 }
734 } else {
735 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700736 mPendingEvent = mInboundQueue.front();
737 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 traceInboundQueueLengthLocked();
739 }
740
741 // Poke user activity for this event.
742 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700743 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 }
746
747 // Now we have an event to dispatch.
748 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700749 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700751 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700753 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700755 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757
758 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700759 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 }
761
762 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700763 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700764 const ConfigurationChangedEntry& typedEntry =
765 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 break;
769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700771 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700772 const DeviceResetEntry& typedEntry =
773 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700775 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700776 break;
777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100779 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700780 std::shared_ptr<FocusEntry> typedEntry =
781 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100782 dispatchFocusLocked(currentTime, typedEntry);
783 done = true;
784 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
785 break;
786 }
787
Prabir Pradhan99987712020-11-10 18:43:05 -0800788 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
789 const auto typedEntry =
790 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
791 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
792 done = true;
793 break;
794 }
795
arthurhungb89ccb02020-12-30 16:19:01 +0800796 case EventEntry::Type::DRAG: {
797 std::shared_ptr<DragEntry> typedEntry =
798 std::static_pointer_cast<DragEntry>(mPendingEvent);
799 dispatchDragLocked(currentTime, typedEntry);
800 done = true;
801 break;
802 }
803
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700804 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700805 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 resetPendingAppSwitchLocked(true);
809 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 } else if (dropReason == DropReason::NOT_DROPPED) {
811 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 }
813 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700814 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700815 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700817 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
818 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700821 break;
822 }
823
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700824 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700825 std::shared_ptr<MotionEntry> motionEntry =
826 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700827 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
828 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700830 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700831 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700833 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
834 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700836 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700837 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
Chris Yef59a2f42020-10-16 12:55:26 -0700839
840 case EventEntry::Type::SENSOR: {
841 std::shared_ptr<SensorEntry> sensorEntry =
842 std::static_pointer_cast<SensorEntry>(mPendingEvent);
843 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
844 dropReason = DropReason::APP_SWITCH;
845 }
846 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
847 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
848 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
849 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
850 dropReason = DropReason::STALE;
851 }
852 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
853 done = true;
854 break;
855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 }
857
858 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700860 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 }
Michael Wright3a981722015-06-10 15:26:13 +0100862 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863
864 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 }
867}
868
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700869/**
870 * Return true if the events preceding this incoming motion event should be dropped
871 * Return false otherwise (the default behaviour)
872 */
873bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700874 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700875 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700876
877 // Optimize case where the current application is unresponsive and the user
878 // decides to touch a window in a different application.
879 // If the application takes too long to catch up then we drop all events preceding
880 // the touch into the other window.
881 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700882 int32_t displayId = motionEntry.displayId;
883 int32_t x = static_cast<int32_t>(
884 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
885 int32_t y = static_cast<int32_t>(
886 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
887 sp<InputWindowHandle> touchedWindowHandle =
888 findTouchedWindowAtLocked(displayId, x, y, nullptr);
889 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890 touchedWindowHandle->getApplicationToken() !=
891 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700892 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 ALOGI("Pruning input queue because user touched a different application while waiting "
894 "for %s",
895 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700896 return true;
897 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898
899 // Alternatively, maybe there's a gesture monitor that could handle this event
900 std::vector<TouchedMonitor> gestureMonitors =
901 findTouchedGestureMonitorsLocked(displayId, {});
902 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
903 sp<Connection> connection =
904 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000905 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700906 // This monitor could take more input. Drop all events preceding this
907 // event, so that gesture monitor could get a chance to receive the stream
908 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
909 "responsive gesture monitor that may handle the event",
910 mAwaitedFocusedApplication->getName().c_str());
911 return true;
912 }
913 }
914 }
915
916 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
917 // yet been processed by some connections, the dispatcher will wait for these motion
918 // events to be processed before dispatching the key event. This is because these motion events
919 // may cause a new window to be launched, which the user might expect to receive focus.
920 // To prevent waiting forever for such events, just send the key to the currently focused window
921 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
922 ALOGD("Received a new pointer down event, stop waiting for events to process and "
923 "just send the pending key event to the focused window.");
924 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700925 }
926 return false;
927}
928
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700929bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700930 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700931 mInboundQueue.push_back(std::move(newEntry));
932 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 traceInboundQueueLengthLocked();
934
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700935 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700936 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 // Optimize app switch latency.
938 // If the application takes too long to catch up then we drop all events preceding
939 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700940 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700942 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700944 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700949 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 mAppSwitchSawKeyDown = false;
951 needWake = true;
952 }
953 }
954 }
955 break;
956 }
957
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700958 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700959 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
960 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100965 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700966 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
967 break;
968 }
969 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800970 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700971 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800972 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
973 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700974 // nothing to do
975 break;
976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 }
978
979 return needWake;
980}
981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700983 // Do not store sensor event in recent queue to avoid flooding the queue.
984 if (entry->type != EventEntry::Type::SENSOR) {
985 mRecentQueue.push_back(entry);
986 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700987 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700988 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
990}
991
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700993 int32_t y, TouchState* touchState,
994 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800995 bool addPortalWindows,
996 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700997 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
998 LOG_ALWAYS_FATAL(
999 "Must provide a valid touch state if adding portal windows or outside targets");
1000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -07001002 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001003 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001004 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001005 continue;
1006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1008 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001009 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010
1011 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001012 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1013 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1014 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001016 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1018 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001019 if (addPortalWindows) {
1020 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001021 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001022 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001023 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 // Found window.
1027 return windowHandle;
1028 }
1029 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001030
Michael Wright44753b12020-07-08 13:48:11 +01001031 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001032 touchState->addOrUpdateWindow(windowHandle,
1033 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1034 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
1038 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001039 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040}
1041
Garfield Tane84e6f92019-08-29 17:28:41 -07001042std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001043 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001044 std::vector<TouchedMonitor> touchedMonitors;
1045
1046 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1047 addGestureMonitors(monitors, touchedMonitors);
1048 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1049 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1050 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1052 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001053 }
1054 return touchedMonitors;
1055}
1056
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001057void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 const char* reason;
1059 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001060 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 reason = "inbound event was dropped because the policy consumed it";
1065 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 case DropReason::DISABLED:
1067 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 ALOGI("Dropped event because input dispatch is disabled.");
1069 }
1070 reason = "inbound event was dropped because input dispatch is disabled";
1071 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 ALOGI("Dropped event because of pending overdue app switch.");
1074 reason = "inbound event was dropped because of pending overdue app switch";
1075 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 ALOGI("Dropped event because the current application is not responding and the user "
1078 "has started interacting with a different application.");
1079 reason = "inbound event was dropped because the current application is not responding "
1080 "and the user has started interacting with a different application";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 ALOGI("Dropped event because it is stale.");
1084 reason = "inbound event was dropped because it is stale";
1085 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001086 case DropReason::NO_POINTER_CAPTURE:
1087 ALOGI("Dropped event because there is no window with Pointer Capture.");
1088 reason = "inbound event was dropped because there is no window with Pointer Capture";
1089 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001090 case DropReason::NOT_DROPPED: {
1091 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001096 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001097 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1099 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001102 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001103 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1104 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1106 synthesizeCancelationEventsForAllConnectionsLocked(options);
1107 } else {
1108 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1109 synthesizeCancelationEventsForAllConnectionsLocked(options);
1110 }
1111 break;
1112 }
Chris Yef59a2f42020-10-16 12:55:26 -07001113 case EventEntry::Type::SENSOR: {
1114 break;
1115 }
arthurhungb89ccb02020-12-30 16:19:01 +08001116 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1117 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001118 break;
1119 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001120 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001121 case EventEntry::Type::CONFIGURATION_CHANGED:
1122 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001123 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 break;
1125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 }
1127}
1128
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001129static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1131 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132}
1133
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001134bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1135 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1136 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1137 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138}
1139
1140bool InputDispatcher::isAppSwitchPendingLocked() {
1141 return mAppSwitchDueTime != LONG_LONG_MAX;
1142}
1143
1144void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1145 mAppSwitchDueTime = LONG_LONG_MAX;
1146
1147#if DEBUG_APP_SWITCH
1148 if (handled) {
1149 ALOGD("App switch has arrived.");
1150 } else {
1151 ALOGD("App switch was abandoned.");
1152 }
1153#endif
1154}
1155
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001157 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158}
1159
1160bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001161 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 return false;
1163 }
1164
1165 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001166 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001167 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001169 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170
1171 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001172 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 return true;
1174}
1175
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001176void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1177 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178}
1179
1180void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001181 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001182 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001183 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 releaseInboundEventLocked(entry);
1185 }
1186 traceInboundQueueLengthLocked();
1187}
1188
1189void InputDispatcher::releasePendingEventLocked() {
1190 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001192 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194}
1195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001198 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199#if DEBUG_DISPATCH_CYCLE
1200 ALOGD("Injected inbound event was dropped.");
1201#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001205 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208}
1209
1210void InputDispatcher::resetKeyRepeatLocked() {
1211 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001212 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214}
1215
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001216std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1217 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218
Michael Wright2e732952014-09-24 13:26:59 -07001219 uint32_t policyFlags = entry->policyFlags &
1220 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 std::shared_ptr<KeyEntry> newEntry =
1223 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1224 entry->source, entry->displayId, policyFlags, entry->action,
1225 entry->flags, entry->keyCode, entry->scanCode,
1226 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 newEntry->syntheticRepeat = true;
1229 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232}
1233
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001234bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238#endif
1239
1240 // Reset key repeating in case a keyboard device was added or removed or something.
1241 resetKeyRepeatLocked();
1242
1243 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001244 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1245 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001247 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 return true;
1249}
1250
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1252 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1255 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256#endif
1257
liushenxiang42232912021-05-21 20:24:09 +08001258 // Reset key repeating in case a keyboard device was disabled or enabled.
1259 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1260 resetKeyRepeatLocked();
1261 }
1262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001263 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 synthesizeCancelationEventsForAllConnectionsLocked(options);
1266 return true;
1267}
1268
Vishnu Nairad321cd2020-08-20 16:40:21 -07001269void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001270 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001271 if (mPendingEvent != nullptr) {
1272 // Move the pending event to the front of the queue. This will give the chance
1273 // for the pending event to get dispatched to the newly focused window
1274 mInboundQueue.push_front(mPendingEvent);
1275 mPendingEvent = nullptr;
1276 }
1277
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278 std::unique_ptr<FocusEntry> focusEntry =
1279 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1280 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001281
1282 // This event should go to the front of the queue, but behind all other focus events
1283 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001285 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 [](const std::shared_ptr<EventEntry>& event) {
1287 return event->type == EventEntry::Type::FOCUS;
1288 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001289
1290 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001291 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001292}
1293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001295 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001296 if (channel == nullptr) {
1297 return; // Window has gone away
1298 }
1299 InputTarget target;
1300 target.inputChannel = channel;
1301 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1302 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001303 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1304 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001305 std::string reason = std::string("reason=").append(entry->reason);
1306 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001307 dispatchEventLocked(currentTime, entry, {target});
1308}
1309
Prabir Pradhan99987712020-11-10 18:43:05 -08001310void InputDispatcher::dispatchPointerCaptureChangedLocked(
1311 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1312 DropReason& dropReason) {
Prabir Pradhanf192a102021-08-06 14:01:18 +00001313 dropReason = DropReason::NOT_DROPPED;
1314
Prabir Pradhan99987712020-11-10 18:43:05 -08001315 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001316 sp<IBinder> token;
Prabir Pradhanf192a102021-08-06 14:01:18 +00001317
1318 if (entry->pointerCaptureRequest.enable) {
1319 // Enable Pointer Capture.
1320 if (haveWindowWithPointerCapture &&
1321 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1322 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1323 "to the window.");
1324 }
1325 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001326 // This can happen if a window requests capture and immediately releases capture.
1327 ALOGW("No window requested Pointer Capture.");
Prabir Pradhanf192a102021-08-06 14:01:18 +00001328 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001329 return;
1330 }
Prabir Pradhanf192a102021-08-06 14:01:18 +00001331 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1332 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1333 return;
1334 }
1335
Vishnu Nairc519ff72021-01-21 08:23:08 -08001336 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001337 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1338 mWindowTokenWithPointerCapture = token;
1339 } else {
Prabir Pradhanf192a102021-08-06 14:01:18 +00001340 // Disable Pointer Capture.
1341 // We do not check if the sequence number matches for requests to disable Pointer Capture
1342 // for two reasons:
1343 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1344 // to disable capture with the same sequence number: one generated by
1345 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1346 // Capture being disabled in InputReader.
1347 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1348 // actual Pointer Capture state that affects events being generated by input devices is
1349 // in InputReader.
1350 if (!haveWindowWithPointerCapture) {
1351 // Pointer capture was already forcefully disabled because of focus change.
1352 dropReason = DropReason::NOT_DROPPED;
1353 return;
1354 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001355 token = mWindowTokenWithPointerCapture;
1356 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanf192a102021-08-06 14:01:18 +00001357 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001358 setPointerCaptureLocked(false);
1359 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001360 }
1361
1362 auto channel = getInputChannelLocked(token);
1363 if (channel == nullptr) {
1364 // Window has gone away, clean up Pointer Capture state.
1365 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanf192a102021-08-06 14:01:18 +00001366 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001367 setPointerCaptureLocked(false);
1368 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001369 return;
1370 }
1371 InputTarget target;
1372 target.inputChannel = channel;
1373 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1374 entry->dispatchInProgress = true;
1375 dispatchEventLocked(currentTime, entry, {target});
1376
1377 dropReason = DropReason::NOT_DROPPED;
1378}
1379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 if (!entry->dispatchInProgress) {
1384 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1385 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1386 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1387 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001388 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 // We have seen two identical key downs in a row which indicates that the device
1390 // driver is automatically generating key repeats itself. We take note of the
1391 // repeat here, but we disable our own next key repeat timer since it is clear that
1392 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001393 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1394 // Make sure we don't get key down from a different device. If a different
1395 // device Id has same key pressed down, the new device Id will replace the
1396 // current one to hold the key repeat with repeat count reset.
1397 // In the future when got a KEY_UP on the device id, drop it and do not
1398 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1400 resetKeyRepeatLocked();
1401 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1402 } else {
1403 // Not a repeat. Save key down state in case we do see a repeat later.
1404 resetKeyRepeatLocked();
1405 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1406 }
1407 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001408 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1409 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001410 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001411#if DEBUG_INBOUND_EVENT_DETAILS
1412 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1413#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 resetKeyRepeatLocked();
1416 }
1417
1418 if (entry->repeatCount == 1) {
1419 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1420 } else {
1421 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1422 }
1423
1424 entry->dispatchInProgress = true;
1425
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001426 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428
1429 // Handle case where the policy asked us to try again later last time.
1430 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1431 if (currentTime < entry->interceptKeyWakeupTime) {
1432 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1433 *nextWakeupTime = entry->interceptKeyWakeupTime;
1434 }
1435 return false; // wait until next wakeup
1436 }
1437 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1438 entry->interceptKeyWakeupTime = 0;
1439 }
1440
1441 // Give the policy a chance to intercept the key.
1442 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1443 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001444 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001445 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001446 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001447 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001448 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001450 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return false; // wait for the command to run
1452 } else {
1453 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1454 }
1455 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001456 if (*dropReason == DropReason::NOT_DROPPED) {
1457 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 }
1459 }
1460
1461 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001462 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001463 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001464 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1465 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001466 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 return true;
1468 }
1469
1470 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001471 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001472 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001473 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return false;
1476 }
1477
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001478 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001479 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 return true;
1481 }
1482
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001483 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001484 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485
1486 // Dispatch the key.
1487 dispatchEventLocked(currentTime, entry, inputTargets);
1488 return true;
1489}
1490
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001491void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001493 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1495 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001496 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1497 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1498 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499#endif
1500}
1501
Chris Yef59a2f42020-10-16 12:55:26 -07001502void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1503 mLock.unlock();
1504
1505 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1506 if (entry->accuracyChanged) {
1507 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1508 }
1509 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1510 entry->hwTimestamp, entry->values);
1511 mLock.lock();
1512}
1513
1514void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1515 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1516#if DEBUG_OUTBOUND_EVENT_DETAILS
1517 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1518 "source=0x%x, sensorType=%s",
1519 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001520 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001521#endif
1522 std::unique_ptr<CommandEntry> commandEntry =
1523 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1524 commandEntry->sensorEntry = entry;
1525 postCommandLocked(std::move(commandEntry));
1526}
1527
1528bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1529#if DEBUG_OUTBOUND_EVENT_DETAILS
1530 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1531 NamedEnum::string(sensorType).c_str());
1532#endif
1533 { // acquire lock
1534 std::scoped_lock _l(mLock);
1535
1536 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1537 std::shared_ptr<EventEntry> entry = *it;
1538 if (entry->type == EventEntry::Type::SENSOR) {
1539 it = mInboundQueue.erase(it);
1540 releaseInboundEventLocked(entry);
1541 }
1542 }
1543 }
1544 return true;
1545}
1546
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001547bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001549 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001551 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 entry->dispatchInProgress = true;
1553
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001554 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 }
1556
1557 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001558 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001559 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1561 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 return true;
1563 }
1564
1565 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1566
1567 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001568 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569
1570 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 if (isPointerEvent) {
1573 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001574 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 } else {
1578 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001580 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 return false;
1584 }
1585
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001586 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001587 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001588 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1589 return true;
1590 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001591 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001592 CancelationOptions::Mode mode(isPointerEvent
1593 ? CancelationOptions::CANCEL_POINTER_EVENTS
1594 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1595 CancelationOptions options(mode, "input event injection failed");
1596 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 return true;
1598 }
1599
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001600 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001601 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001603 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001604 std::unordered_map<int32_t, TouchState>::iterator it =
1605 mTouchStatesByDisplay.find(entry->displayId);
1606 if (it != mTouchStatesByDisplay.end()) {
1607 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001608 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001609 // The event has gone through these portal windows, so we add monitoring targets of
1610 // the corresponding displays as well.
1611 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001612 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001613 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001615 }
1616 }
1617 }
1618 }
1619
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 // Dispatch the motion.
1621 if (conflictingPointerActions) {
1622 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001623 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 synthesizeCancelationEventsForAllConnectionsLocked(options);
1625 }
1626 dispatchEventLocked(currentTime, entry, inputTargets);
1627 return true;
1628}
1629
arthurhungb89ccb02020-12-30 16:19:01 +08001630void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1631 bool isExiting, const MotionEntry& motionEntry) {
1632 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1633 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1634 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1635 PointerCoords pointerCoords;
1636 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1637 pointerCoords.transform(windowHandle->getInfo()->transform);
1638
1639 std::unique_ptr<DragEntry> dragEntry =
1640 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1641 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1642 pointerCoords.getY());
1643
1644 enqueueInboundEventLocked(std::move(dragEntry));
1645}
1646
1647void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1648 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1649 if (channel == nullptr) {
1650 return; // Window has gone away
1651 }
1652 InputTarget target;
1653 target.inputChannel = channel;
1654 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1655 entry->dispatchInProgress = true;
1656 dispatchEventLocked(currentTime, entry, {target});
1657}
1658
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001659void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001661 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 ", policyFlags=0x%x, "
1663 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1664 "metaState=0x%x, buttonState=0x%x,"
1665 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001666 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1667 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1668 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001672 "x=%f, y=%f, pressure=%f, size=%f, "
1673 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1674 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1676 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1677 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1678 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1679 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1680 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1681 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1682 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1683 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1684 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 }
1686#endif
1687}
1688
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001689void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1690 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001691 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001692 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693#if DEBUG_DISPATCH_CYCLE
1694 ALOGD("dispatchEventToCurrentInputTargets");
1695#endif
1696
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001697 updateInteractionTokensLocked(*eventEntry, inputTargets);
1698
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1700
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001703 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001704 sp<Connection> connection =
1705 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001706 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001707 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001709 if (DEBUG_FOCUS) {
1710 ALOGD("Dropping event delivery to target with channel '%s' because it "
1711 "is no longer registered with the input dispatcher.",
1712 inputTarget.inputChannel->getName().c_str());
1713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 }
1715 }
1716}
1717
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001718void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1719 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1720 // If the policy decides to close the app, we will get a channel removal event via
1721 // unregisterInputChannel, and will clean up the connection that way. We are already not
1722 // sending new pointers to the connection when it blocked, but focused events will continue to
1723 // pile up.
1724 ALOGW("Canceling events for %s because it is unresponsive",
1725 connection->inputChannel->getName().c_str());
1726 if (connection->status == Connection::STATUS_NORMAL) {
1727 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1728 "application not responding");
1729 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
1731}
1732
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001733void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001734 if (DEBUG_FOCUS) {
1735 ALOGD("Resetting ANR timeouts.");
1736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
1738 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001739 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001740 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741}
1742
Tiger Huang721e26f2018-07-24 22:26:19 +08001743/**
1744 * Get the display id that the given event should go to. If this event specifies a valid display id,
1745 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1746 * Focused display is the display that the user most recently interacted with.
1747 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001748int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001749 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001750 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001751 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001752 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1753 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 break;
1755 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001756 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1758 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001759 break;
1760 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001761 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001762 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001763 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001764 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001765 case EventEntry::Type::SENSOR:
1766 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001767 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001768 return ADISPLAY_ID_NONE;
1769 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001770 }
1771 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1772}
1773
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001774bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1775 const char* focusedWindowName) {
1776 if (mAnrTracker.empty()) {
1777 // already processed all events that we waited for
1778 mKeyIsWaitingForEventsTimeout = std::nullopt;
1779 return false;
1780 }
1781
1782 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1783 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001784 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001785 mKeyIsWaitingForEventsTimeout = currentTime +
1786 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1787 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001788 return true;
1789 }
1790
1791 // We still have pending events, and already started the timer
1792 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1793 return true; // Still waiting
1794 }
1795
1796 // Waited too long, and some connection still hasn't processed all motions
1797 // Just send the key to the focused window
1798 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1799 focusedWindowName);
1800 mKeyIsWaitingForEventsTimeout = std::nullopt;
1801 return false;
1802}
1803
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1805 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1806 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001807 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808
Tiger Huang721e26f2018-07-24 22:26:19 +08001809 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001810 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001811 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001812 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1813
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 // If there is no currently focused window and no focused application
1815 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001816 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1817 ALOGI("Dropping %s event because there is no focused window or focused application in "
1818 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001819 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001820 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1824 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1825 // start interacting with another application via touch (app switch). This code can be removed
1826 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1827 // an app is expected to have a focused window.
1828 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1829 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1830 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001831 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1832 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1833 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001834 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001835 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 ALOGW("Waiting because no window has focus but %s may eventually add a "
1837 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001838 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1842 // Already raised ANR. Drop the event
1843 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001844 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001846 } else {
1847 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 }
1850 }
1851
1852 // we have a valid, non-null focused window
1853 resetNoFocusedWindowTimeoutLocked();
1854
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001856 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 }
1859
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001860 if (focusedWindowHandle->getInfo()->paused) {
1861 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001863 }
1864
1865 // If the event is a key event, then we must wait for all previous events to
1866 // complete before delivering it because previous events may have the
1867 // side-effect of transferring focus to a different window and we want to
1868 // ensure that the following keys are sent to the new window.
1869 //
1870 // Suppose the user touches a button in a window then immediately presses "A".
1871 // If the button causes a pop-up window to appear then we want to ensure that
1872 // the "A" key is delivered to the new pop-up window. This is because users
1873 // often anticipate pending UI changes when typing on a keyboard.
1874 // To obtain this behavior, we must serialize key events with respect to all
1875 // prior input events.
1876 if (entry.type == EventEntry::Type::KEY) {
1877 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1878 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
1882
1883 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001884 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001885 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1886 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887
1888 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001889 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890}
1891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892/**
1893 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1894 * that are currently unresponsive.
1895 */
1896std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1897 const std::vector<TouchedMonitor>& monitors) const {
1898 std::vector<TouchedMonitor> responsiveMonitors;
1899 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1900 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1901 sp<Connection> connection = getConnectionLocked(
1902 monitor.monitor.inputChannel->getConnectionToken());
1903 if (connection == nullptr) {
1904 ALOGE("Could not find connection for monitor %s",
1905 monitor.monitor.inputChannel->getName().c_str());
1906 return false;
1907 }
1908 if (!connection->responsive) {
1909 ALOGW("Unresponsive monitor %s will not get the new gesture",
1910 connection->inputChannel->getName().c_str());
1911 return false;
1912 }
1913 return true;
1914 });
1915 return responsiveMonitors;
1916}
1917
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001918InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1919 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1920 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001921 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 enum InjectionPermission {
1923 INJECTION_PERMISSION_UNKNOWN,
1924 INJECTION_PERMISSION_GRANTED,
1925 INJECTION_PERMISSION_DENIED
1926 };
1927
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 // For security reasons, we defer updating the touch state until we are sure that
1929 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001930 int32_t displayId = entry.displayId;
1931 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1933
1934 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001937 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1938 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001940 // Copy current touch state into tempTouchState.
1941 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1942 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001943 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001945 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1946 mTouchStatesByDisplay.find(displayId);
1947 if (oldStateIt != mTouchStatesByDisplay.end()) {
1948 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001949 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001950 }
1951
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 bool isSplit = tempTouchState.split;
1953 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1954 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1955 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001956 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1957 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1958 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1959 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1960 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001961 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 bool wrongDevice = false;
1963 if (newGesture) {
1964 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001965 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001966 ALOGI("Dropping event because a pointer for a different device is already down "
1967 "in display %" PRId32,
1968 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001969 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 switchedDevice = false;
1972 wrongDevice = true;
1973 goto Failed;
1974 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001975 tempTouchState.reset();
1976 tempTouchState.down = down;
1977 tempTouchState.deviceId = entry.deviceId;
1978 tempTouchState.source = entry.source;
1979 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001981 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001982 ALOGI("Dropping move event because a pointer for a different device is already active "
1983 "in display %" PRId32,
1984 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001985 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001987 switchedDevice = false;
1988 wrongDevice = true;
1989 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 }
1991
1992 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1993 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1994
Garfield Tan00f511d2019-06-12 16:55:40 -07001995 int32_t x;
1996 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001998 // Always dispatch mouse events to cursor position.
1999 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002000 x = int32_t(entry.xCursorPosition);
2001 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002002 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002003 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2004 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002005 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002006 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07002007 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002008 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2009 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002010
2011 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002012 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002013 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002016 if (newTouchedWindowHandle != nullptr &&
2017 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002018 // New window supports splitting, but we should never split mouse events.
2019 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 } else if (isSplit) {
2021 // New window does not support splitting but we have already split events.
2022 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002023 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 }
2025
2026 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002027 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002029 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002030 }
2031
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002032 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2033 ALOGI("Not sending touch event to %s because it is paused",
2034 newTouchedWindowHandle->getName().c_str());
2035 newTouchedWindowHandle = nullptr;
2036 }
2037
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002038 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002039 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002040 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2041 if (!isResponsive) {
2042 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002043 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2044 newTouchedWindowHandle = nullptr;
2045 }
2046 }
2047
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002048 // Drop events that can't be trusted due to occlusion
2049 if (newTouchedWindowHandle != nullptr &&
2050 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2051 TouchOcclusionInfo occlusionInfo =
2052 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002053 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002054 if (DEBUG_TOUCH_OCCLUSION) {
2055 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2056 for (const auto& log : occlusionInfo.debugInfo) {
2057 ALOGD("%s", log.c_str());
2058 }
2059 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002060 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2061 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2062 ALOGW("Dropping untrusted touch event due to %s/%d",
2063 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2064 newTouchedWindowHandle = nullptr;
2065 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002066 }
2067 }
2068
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 // Also don't send the new touch event to unresponsive gesture monitors
2070 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2071
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2073 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074 "(%d, %d) in display %" PRId32 ".",
2075 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 goto Failed;
2078 }
2079
2080 if (newTouchedWindowHandle != nullptr) {
2081 // Set target flags.
2082 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2083 if (isSplit) {
2084 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002086 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2087 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2088 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2089 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2090 }
2091
2092 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002093 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2094 newHoverWindowHandle = nullptr;
2095 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002096 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002097 }
2098
2099 // Update the temporary touch state.
2100 BitSet32 pointerIds;
2101 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002102 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002103 pointerIds.markBit(pointerId);
2104 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002105 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
2107
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002108 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 } else {
2110 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2111
2112 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002113 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002114 if (DEBUG_FOCUS) {
2115 ALOGD("Dropping event because the pointer is not down or we previously "
2116 "dropped the pointer down event in display %" PRId32,
2117 displayId);
2118 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002119 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 goto Failed;
2121 }
2122
arthurhung6d4bed92021-03-17 11:59:33 +08002123 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002124
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002126 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002128 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2129 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130
2131 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002132 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002133 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002134 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2135 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002136 if (DEBUG_FOCUS) {
2137 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2138 oldTouchedWindowHandle->getName().c_str(),
2139 newTouchedWindowHandle->getName().c_str(), displayId);
2140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002142 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2143 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2144 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145
2146 // Make a slippery entrance into the new window.
2147 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2148 isSplit = true;
2149 }
2150
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002151 int32_t targetFlags =
2152 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 if (isSplit) {
2154 targetFlags |= InputTarget::FLAG_SPLIT;
2155 }
2156 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2157 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002158 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2159 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161
2162 BitSet32 pointerIds;
2163 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002164 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002166 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 }
2168 }
2169 }
2170
2171 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002172 // Let the previous window know that the hover sequence is over, unless we already did it
2173 // when dispatching it as is to newTouchedWindowHandle.
2174 if (mLastHoverWindowHandle != nullptr &&
2175 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2176 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177#if DEBUG_HOVER
2178 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002181 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2182 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
2184
Garfield Tandf26e862020-07-01 20:18:19 -07002185 // Let the new window know that the hover sequence is starting, unless we already did it
2186 // when dispatching it as is to newTouchedWindowHandle.
2187 if (newHoverWindowHandle != nullptr &&
2188 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2189 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190#if DEBUG_HOVER
2191 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002192 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2195 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2196 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198 }
2199
2200 // Check permission to inject into all touched foreground windows and ensure there
2201 // is at least one touched foreground window.
2202 {
2203 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2206 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002207 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002208 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 injectionPermission = INJECTION_PERMISSION_DENIED;
2210 goto Failed;
2211 }
2212 }
2213 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002214 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002215 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002216 ALOGI("Dropping event because there is no touched foreground window in display "
2217 "%" PRId32 " or gesture monitor to receive it.",
2218 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002219 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 goto Failed;
2221 }
2222
2223 // Permission granted to injection into all touched foreground windows.
2224 injectionPermission = INJECTION_PERMISSION_GRANTED;
2225 }
2226
2227 // Check whether windows listening for outside touches are owned by the same UID. If it is
2228 // set the policy flag that we will not reveal coordinate information to this window.
2229 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2230 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002231 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002232 if (foregroundWindowHandle) {
2233 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002234 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002235 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2236 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2237 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002238 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2239 InputTarget::FLAG_ZERO_COORDS,
2240 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 }
2243 }
2244 }
2245 }
2246
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // If this is the first pointer going down and the touched window has a wallpaper
2248 // then also add the touched wallpaper windows so they are locked in for the duration
2249 // of the touch gesture.
2250 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2251 // engine only supports touch events. We would need to add a mechanism similar
2252 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2253 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2254 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002255 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002256 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002257 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002258 getWindowHandlesLocked(displayId);
2259 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002261 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002262 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002263 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 .addOrUpdateWindow(windowHandle,
2265 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2266 InputTarget::
2267 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2268 InputTarget::FLAG_DISPATCH_AS_IS,
2269 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271 }
2272 }
2273 }
2274
2275 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002276 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002283 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002286 }
2287
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 // Drop the outside or hover touch windows since we will not care about them
2289 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002290 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291
2292Failed:
2293 // Check injection permission once and for all.
2294 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002295 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 injectionPermission = INJECTION_PERMISSION_GRANTED;
2297 } else {
2298 injectionPermission = INJECTION_PERMISSION_DENIED;
2299 }
2300 }
2301
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002302 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2303 return injectionResult;
2304 }
2305
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002307 if (!wrongDevice) {
2308 if (switchedDevice) {
2309 if (DEBUG_FOCUS) {
2310 ALOGD("Conflicting pointer actions: Switched to a different device.");
2311 }
2312 *outConflictingPointerActions = true;
2313 }
2314
2315 if (isHoverAction) {
2316 // Started hovering, therefore no longer down.
2317 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002318 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002319 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2320 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 *outConflictingPointerActions = true;
2323 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002324 tempTouchState.reset();
2325 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2326 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2327 tempTouchState.deviceId = entry.deviceId;
2328 tempTouchState.source = entry.source;
2329 tempTouchState.displayId = displayId;
2330 }
2331 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2332 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2333 // All pointers up or canceled.
2334 tempTouchState.reset();
2335 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2336 // First pointer went down.
2337 if (oldState && oldState->down) {
2338 if (DEBUG_FOCUS) {
2339 ALOGD("Conflicting pointer actions: Down received while already down.");
2340 }
2341 *outConflictingPointerActions = true;
2342 }
2343 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2344 // One pointer went up.
2345 if (isSplit) {
2346 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2347 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002349 for (size_t i = 0; i < tempTouchState.windows.size();) {
2350 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2351 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2352 touchedWindow.pointerIds.clearBit(pointerId);
2353 if (touchedWindow.pointerIds.isEmpty()) {
2354 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2355 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002360 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002361 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002362
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002363 // Save changes unless the action was scroll in which case the temporary touch
2364 // state was only valid for this one action.
2365 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2366 if (tempTouchState.displayId >= 0) {
2367 mTouchStatesByDisplay[displayId] = tempTouchState;
2368 } else {
2369 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002373 // Update hover state.
2374 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
2376
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 return injectionResult;
2378}
2379
arthurhung6d4bed92021-03-17 11:59:33 +08002380void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2381 const sp<InputWindowHandle> dropWindow =
2382 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2383 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2384 true /*ignoreDragWindow*/);
2385 if (dropWindow) {
2386 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2387 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002388 } else {
2389 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002390 }
2391 mDragState.reset();
2392}
2393
2394void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2395 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002396 return;
2397 }
2398
arthurhung6d4bed92021-03-17 11:59:33 +08002399 if (!mDragState->isStartDrag) {
2400 mDragState->isStartDrag = true;
2401 mDragState->isStylusButtonDownAtStart =
2402 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2403 }
2404
arthurhungb89ccb02020-12-30 16:19:01 +08002405 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2406 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2407 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2408 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002409 // Handle the special case : stylus button no longer pressed.
2410 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2411 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2412 finishDragAndDrop(entry.displayId, x, y);
2413 return;
2414 }
2415
arthurhungb89ccb02020-12-30 16:19:01 +08002416 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002417 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002418 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2419 true /*ignoreDragWindow*/);
2420 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002421 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2422 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2423 if (mDragState->dragHoverWindowHandle != nullptr) {
2424 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2425 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002426 }
arthurhung6d4bed92021-03-17 11:59:33 +08002427 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002428 }
2429 // enqueue drag location if needed.
2430 if (hoverWindowHandle != nullptr) {
2431 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2432 }
arthurhung6d4bed92021-03-17 11:59:33 +08002433 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2434 finishDragAndDrop(entry.displayId, x, y);
2435 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002436 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002437 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002438 }
2439}
2440
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002442 int32_t targetFlags, BitSet32 pointerIds,
2443 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002444 std::vector<InputTarget>::iterator it =
2445 std::find_if(inputTargets.begin(), inputTargets.end(),
2446 [&windowHandle](const InputTarget& inputTarget) {
2447 return inputTarget.inputChannel->getConnectionToken() ==
2448 windowHandle->getToken();
2449 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002450
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002451 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002452
2453 if (it == inputTargets.end()) {
2454 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002455 std::shared_ptr<InputChannel> inputChannel =
2456 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002457 if (inputChannel == nullptr) {
2458 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2459 return;
2460 }
2461 inputTarget.inputChannel = inputChannel;
2462 inputTarget.flags = targetFlags;
2463 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002464 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002465 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002466 inputTargets.push_back(inputTarget);
2467 it = inputTargets.end() - 1;
2468 }
2469
2470 ALOG_ASSERT(it->flags == targetFlags);
2471 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2472
chaviw1ff3d1e2020-07-01 15:53:47 -07002473 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474}
2475
Michael Wright3dd60e22019-03-27 22:06:44 +00002476void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002477 int32_t displayId, float xOffset,
2478 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002479 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2480 mGlobalMonitorsByDisplay.find(displayId);
2481
2482 if (it != mGlobalMonitorsByDisplay.end()) {
2483 const std::vector<Monitor>& monitors = it->second;
2484 for (const Monitor& monitor : monitors) {
2485 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 }
2488}
2489
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2491 float yOffset,
2492 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002493 InputTarget target;
2494 target.inputChannel = monitor.inputChannel;
2495 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002496 ui::Transform t;
2497 t.set(xOffset, yOffset);
2498 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002499 inputTargets.push_back(target);
2500}
2501
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002503 const InjectionState* injectionState) {
2504 if (injectionState &&
2505 (windowHandle == nullptr ||
2506 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2507 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002508 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002510 "owned by uid %d",
2511 injectionState->injectorPid, injectionState->injectorUid,
2512 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 } else {
2514 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002515 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 }
2517 return false;
2518 }
2519 return true;
2520}
2521
Robert Carrc9bf1d32020-04-13 17:21:08 -07002522/**
2523 * Indicate whether one window handle should be considered as obscuring
2524 * another window handle. We only check a few preconditions. Actually
2525 * checking the bounds is left to the caller.
2526 */
2527static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2528 const sp<InputWindowHandle>& otherHandle) {
2529 // Compare by token so cloned layers aren't counted
2530 if (haveSameToken(windowHandle, otherHandle)) {
2531 return false;
2532 }
2533 auto info = windowHandle->getInfo();
2534 auto otherInfo = otherHandle->getInfo();
2535 if (!otherInfo->visible) {
2536 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002537 } else if (otherInfo->alpha == 0 &&
2538 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2539 // Those act as if they were invisible, so we don't need to flag them.
2540 // We do want to potentially flag touchable windows even if they have 0
2541 // opacity, since they can consume touches and alter the effects of the
2542 // user interaction (eg. apps that rely on
2543 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2544 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2545 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002546 } else if (info->ownerUid == otherInfo->ownerUid) {
2547 // If ownerUid is the same we don't generate occlusion events as there
2548 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002549 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002550 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002551 return false;
2552 } else if (otherInfo->displayId != info->displayId) {
2553 return false;
2554 }
2555 return true;
2556}
2557
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002558/**
2559 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2560 * untrusted, one should check:
2561 *
2562 * 1. If result.hasBlockingOcclusion is true.
2563 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2564 * BLOCK_UNTRUSTED.
2565 *
2566 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2567 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2568 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2569 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2570 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2571 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2572 *
2573 * If neither of those is true, then it means the touch can be allowed.
2574 */
2575InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2576 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002577 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2578 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002579 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2580 TouchOcclusionInfo info;
2581 info.hasBlockingOcclusion = false;
2582 info.obscuringOpacity = 0;
2583 info.obscuringUid = -1;
2584 std::map<int32_t, float> opacityByUid;
2585 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2586 if (windowHandle == otherHandle) {
2587 break; // All future windows are below us. Exit early.
2588 }
2589 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002590 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2591 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002592 if (DEBUG_TOUCH_OCCLUSION) {
2593 info.debugInfo.push_back(
2594 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2595 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002596 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2597 // we perform the checks below to see if the touch can be propagated or not based on the
2598 // window's touch occlusion mode
2599 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2600 info.hasBlockingOcclusion = true;
2601 info.obscuringUid = otherInfo->ownerUid;
2602 info.obscuringPackage = otherInfo->packageName;
2603 break;
2604 }
2605 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2606 uint32_t uid = otherInfo->ownerUid;
2607 float opacity =
2608 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2609 // Given windows A and B:
2610 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2611 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2612 opacityByUid[uid] = opacity;
2613 if (opacity > info.obscuringOpacity) {
2614 info.obscuringOpacity = opacity;
2615 info.obscuringUid = uid;
2616 info.obscuringPackage = otherInfo->packageName;
2617 }
2618 }
2619 }
2620 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002621 if (DEBUG_TOUCH_OCCLUSION) {
2622 info.debugInfo.push_back(
2623 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2624 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002625 return info;
2626}
2627
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002628std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2629 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002630 return StringPrintf(INDENT2
2631 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2632 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2633 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2634 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002635 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002636 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002637 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002638 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2639 info->frameTop, info->frameRight, info->frameBottom,
2640 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002641 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2642 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2643 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002644}
2645
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002646bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2647 if (occlusionInfo.hasBlockingOcclusion) {
2648 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2649 occlusionInfo.obscuringUid);
2650 return false;
2651 }
2652 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2653 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2654 "%.2f, maximum allowed = %.2f)",
2655 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2656 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2657 return false;
2658 }
2659 return true;
2660}
2661
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002662bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2663 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002665 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002666 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002667 if (windowHandle == otherHandle) {
2668 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002671 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002672 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 return true;
2674 }
2675 }
2676 return false;
2677}
2678
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002679bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2680 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002681 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002682 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002683 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002684 if (windowHandle == otherHandle) {
2685 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002686 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002687 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002688 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002689 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002690 return true;
2691 }
2692 }
2693 return false;
2694}
2695
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002696std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002697 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002699 if (applicationHandle != nullptr) {
2700 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002701 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 } else {
2703 return applicationHandle->getName();
2704 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002705 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002706 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002708 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 }
2710}
2711
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002712void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002713 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002714 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2715 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002716 // Focus or pointer capture changed events are passed to apps, but do not represent user
2717 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002718 return;
2719 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002720 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002721 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002722 if (focusedWindowHandle != nullptr) {
2723 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002724 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002726 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#endif
2728 return;
2729 }
2730 }
2731
2732 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002733 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002734 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002735 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2736 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 return;
2738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002740 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 eventType = USER_ACTIVITY_EVENT_TOUCH;
2742 }
2743 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002745 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002746 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2747 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002748 return;
2749 }
2750 eventType = USER_ACTIVITY_EVENT_BUTTON;
2751 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002753 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002754 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002755 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002756 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002757 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2758 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002759 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002760 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002761 break;
2762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 }
2764
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002765 std::unique_ptr<CommandEntry> commandEntry =
2766 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002767 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002769 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002770 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771}
2772
2773void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002774 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002775 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002776 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002777 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002779 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002780 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002781 ATRACE_NAME(message.c_str());
2782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783#if DEBUG_DISPATCH_CYCLE
2784 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002785 "globalScaleFactor=%f, pointerIds=0x%x %s",
2786 connection->getInputChannelName().c_str(), inputTarget.flags,
2787 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2788 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789#endif
2790
2791 // Skip this event if the connection status is not normal.
2792 // We don't want to enqueue additional outbound events if the connection is broken.
2793 if (connection->status != Connection::STATUS_NORMAL) {
2794#if DEBUG_DISPATCH_CYCLE
2795 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002796 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797#endif
2798 return;
2799 }
2800
2801 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002802 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2803 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2804 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002805 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002807 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002808 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002809 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002810 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 if (!splitMotionEntry) {
2812 return; // split event was dropped
2813 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002814 if (DEBUG_FOCUS) {
2815 ALOGD("channel '%s' ~ Split motion event.",
2816 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002817 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002818 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002819 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2820 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 return;
2822 }
2823 }
2824
2825 // Not splitting. Enqueue dispatch entries for the event as is.
2826 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2827}
2828
2829void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002831 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002832 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002833 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002835 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002836 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002837 ATRACE_NAME(message.c_str());
2838 }
2839
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002840 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841
2842 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002843 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002845 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002847 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002849 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002850 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002851 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002852 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002853 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
2856 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002857 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 startDispatchCycleLocked(currentTime, connection);
2859 }
2860}
2861
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002862void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002863 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002864 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002865 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002866 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002867 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2868 connection->getInputChannelName().c_str(),
2869 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002870 ATRACE_NAME(message.c_str());
2871 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002872 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 if (!(inputTargetFlags & dispatchMode)) {
2874 return;
2875 }
2876 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2877
2878 // This is a new event.
2879 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002880 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002881 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002883 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2884 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002885 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002887 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002888 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002889 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002890 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002891 dispatchEntry->resolvedAction = keyEntry.action;
2892 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2895 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2898 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 return; // skip the inconsistent event
2901 }
2902 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002905 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002906 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002907 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2908 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2909 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2910 static_cast<int32_t>(IdGenerator::Source::OTHER);
2911 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2913 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2914 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2915 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2916 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2917 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2918 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2919 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2920 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2921 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2922 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002923 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002924 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 }
2926 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002927 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2928 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2931 "event",
2932 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002934 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2935 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002939 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002940 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2941 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2942 }
2943 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2944 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2948 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2951 "event",
2952 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 return; // skip the inconsistent event
2955 }
2956
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002957 dispatchEntry->resolvedEventId =
2958 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2959 ? mIdGenerator.nextId()
2960 : motionEntry.id;
2961 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2962 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2963 ") to MotionEvent(id=0x%" PRIx32 ").",
2964 motionEntry.id, dispatchEntry->resolvedEventId);
2965 ATRACE_NAME(message.c_str());
2966 }
2967
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002968 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2969 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2970 // Skip reporting pointer down outside focus to the policy.
2971 break;
2972 }
2973
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002974 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002975 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976
2977 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002979 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002980 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2981 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002982 break;
2983 }
Chris Yef59a2f42020-10-16 12:55:26 -07002984 case EventEntry::Type::SENSOR: {
2985 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2986 break;
2987 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002988 case EventEntry::Type::CONFIGURATION_CHANGED:
2989 case EventEntry::Type::DEVICE_RESET: {
2990 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002991 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002992 break;
2993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995
2996 // Remember that we are waiting for this dispatch to complete.
2997 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002998 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999 }
3000
3001 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003002 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003003 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003004}
3005
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003006/**
3007 * This function is purely for debugging. It helps us understand where the user interaction
3008 * was taking place. For example, if user is touching launcher, we will see a log that user
3009 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3010 * We will see both launcher and wallpaper in that list.
3011 * Once the interaction with a particular set of connections starts, no new logs will be printed
3012 * until the set of interacted connections changes.
3013 *
3014 * The following items are skipped, to reduce the logspam:
3015 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3016 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3017 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3018 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3019 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003020 */
3021void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3022 const std::vector<InputTarget>& targets) {
3023 // Skip ACTION_UP events, and all events other than keys and motions
3024 if (entry.type == EventEntry::Type::KEY) {
3025 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3026 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3027 return;
3028 }
3029 } else if (entry.type == EventEntry::Type::MOTION) {
3030 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3031 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3032 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3033 return;
3034 }
3035 } else {
3036 return; // Not a key or a motion
3037 }
3038
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003039 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003040 std::vector<sp<Connection>> newConnections;
3041 for (const InputTarget& target : targets) {
3042 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3043 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3044 continue; // Skip windows that receive ACTION_OUTSIDE
3045 }
3046
3047 sp<IBinder> token = target.inputChannel->getConnectionToken();
3048 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003049 if (connection == nullptr) {
3050 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003051 }
3052 newConnectionTokens.insert(std::move(token));
3053 newConnections.emplace_back(connection);
3054 }
3055 if (newConnectionTokens == mInteractionConnectionTokens) {
3056 return; // no change
3057 }
3058 mInteractionConnectionTokens = newConnectionTokens;
3059
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003060 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003061 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003062 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003063 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003064 std::string message = "Interaction with: " + targetList;
3065 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003066 message += "<none>";
3067 }
3068 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3069}
3070
chaviwfd6d3512019-03-25 13:23:49 -07003071void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003072 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003073 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003074 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3075 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003076 return;
3077 }
3078
Vishnu Nairc519ff72021-01-21 08:23:08 -08003079 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003080 if (focusedToken == token) {
3081 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003082 return;
3083 }
3084
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003085 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3086 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003087 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003088 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089}
3090
3091void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003093 if (ATRACE_ENABLED()) {
3094 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003096 ATRACE_NAME(message.c_str());
3097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100#endif
3101
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003102 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3103 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003105 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003106 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003107 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
3109 // Publish the event.
3110 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003111 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3112 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003113 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003114 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3115 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003118 status = connection->inputPublisher
3119 .publishKeyEvent(dispatchEntry->seq,
3120 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3121 keyEntry.source, keyEntry.displayId,
3122 std::move(hmac), dispatchEntry->resolvedAction,
3123 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3124 keyEntry.scanCode, keyEntry.metaState,
3125 keyEntry.repeatCount, keyEntry.downTime,
3126 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
3129
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003130 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003134 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135
chaviw82357092020-01-28 13:13:06 -08003136 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003137 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3139 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003140 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003141 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3142 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003143 // Don't apply window scale here since we don't want scale to affect raw
3144 // coordinates. The scale will be sent back to the client and applied
3145 // later when requesting relative coordinates.
3146 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3147 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003148 }
3149 usingCoords = scaledCoords;
3150 }
3151 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 // We don't want the dispatch target to know.
3153 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003154 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 scaledCoords[i].clear();
3156 }
3157 usingCoords = scaledCoords;
3158 }
3159 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003160
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162
3163 // Publish the motion event.
3164 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003165 .publishMotionEvent(dispatchEntry->seq,
3166 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003167 motionEntry.deviceId, motionEntry.source,
3168 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003169 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003170 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003172 motionEntry.edgeFlags, motionEntry.metaState,
3173 motionEntry.buttonState,
3174 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003175 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003176 motionEntry.xPrecision, motionEntry.yPrecision,
3177 motionEntry.xCursorPosition,
3178 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003179 dispatchEntry->displaySize.x,
3180 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 motionEntry.downTime, motionEntry.eventTime,
3182 motionEntry.pointerCount,
3183 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 break;
3185 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003186
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003187 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003189 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003190 focusEntry.id,
3191 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003192 mInTouchMode);
3193 break;
3194 }
3195
Prabir Pradhan99987712020-11-10 18:43:05 -08003196 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3197 const auto& captureEntry =
3198 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3199 status = connection->inputPublisher
3200 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhanf192a102021-08-06 14:01:18 +00003201 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003202 break;
3203 }
3204
arthurhungb89ccb02020-12-30 16:19:01 +08003205 case EventEntry::Type::DRAG: {
3206 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3207 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3208 dragEntry.id, dragEntry.x,
3209 dragEntry.y,
3210 dragEntry.isExiting);
3211 break;
3212 }
3213
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003214 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003215 case EventEntry::Type::DEVICE_RESET:
3216 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003217 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003218 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
3222
3223 // Check the result.
3224 if (status) {
3225 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003226 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 "This is unexpected because the wait queue is empty, so the pipe "
3229 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003230 "event to it, status=%s(%d)",
3231 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3232 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3234 } else {
3235 // Pipe is full and we are waiting for the app to finish process some events
3236 // before sending more events to it.
3237#if DEBUG_DISPATCH_CYCLE
3238 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 "waiting for the application to catch up",
3240 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
3243 } else {
3244 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003245 "status=%s(%d)",
3246 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3247 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3249 }
3250 return;
3251 }
3252
3253 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003254 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3255 connection->outboundQueue.end(),
3256 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003257 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003258 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003259 if (connection->responsive) {
3260 mAnrTracker.insert(dispatchEntry->timeoutTime,
3261 connection->inputChannel->getConnectionToken());
3262 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003263 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 }
3265}
3266
chaviw09c8d2d2020-08-24 15:48:26 -07003267std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3268 size_t size;
3269 switch (event.type) {
3270 case VerifiedInputEvent::Type::KEY: {
3271 size = sizeof(VerifiedKeyEvent);
3272 break;
3273 }
3274 case VerifiedInputEvent::Type::MOTION: {
3275 size = sizeof(VerifiedMotionEvent);
3276 break;
3277 }
3278 }
3279 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3280 return mHmacKeyManager.sign(start, size);
3281}
3282
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003283const std::array<uint8_t, 32> InputDispatcher::getSignature(
3284 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3285 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3286 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3287 // Only sign events up and down events as the purely move events
3288 // are tied to their up/down counterparts so signing would be redundant.
3289 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3290 verifiedEvent.actionMasked = actionMasked;
3291 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003292 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003293 }
3294 return INVALID_HMAC;
3295}
3296
3297const std::array<uint8_t, 32> InputDispatcher::getSignature(
3298 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3299 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3300 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3301 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003302 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003303}
3304
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003307 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308#if DEBUG_DISPATCH_CYCLE
3309 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311#endif
3312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 if (connection->status == Connection::STATUS_BROKEN ||
3314 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 return;
3316 }
3317
3318 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003319 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320}
3321
3322void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 const sp<Connection>& connection,
3324 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325#if DEBUG_DISPATCH_CYCLE
3326 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328#endif
3329
3330 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003331 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003332 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003333 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003334 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335
3336 // The connection appears to be unrecoverably broken.
3337 // Ignore already broken or zombie connections.
3338 if (connection->status == Connection::STATUS_NORMAL) {
3339 connection->status = Connection::STATUS_BROKEN;
3340
3341 if (notify) {
3342 // Notify other system components.
3343 onDispatchCycleBrokenLocked(currentTime, connection);
3344 }
3345 }
3346}
3347
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003348void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3349 while (!queue.empty()) {
3350 DispatchEntry* dispatchEntry = queue.front();
3351 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003352 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
3354}
3355
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003356void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003358 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 }
3360 delete dispatchEntry;
3361}
3362
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003363int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3364 std::scoped_lock _l(mLock);
3365 sp<Connection> connection = getConnectionLocked(connectionToken);
3366 if (connection == nullptr) {
3367 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3368 connectionToken.get(), events);
3369 return 0; // remove the callback
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003372 bool notify;
3373 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3374 if (!(events & ALOOPER_EVENT_INPUT)) {
3375 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3376 "events=0x%x",
3377 connection->getInputChannelName().c_str(), events);
3378 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
3380
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003381 nsecs_t currentTime = now();
3382 bool gotOne = false;
3383 status_t status = OK;
3384 for (;;) {
3385 Result<InputPublisher::ConsumerResponse> result =
3386 connection->inputPublisher.receiveConsumerResponse();
3387 if (!result.ok()) {
3388 status = result.error().code();
3389 break;
3390 }
3391
3392 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3393 const InputPublisher::Finished& finish =
3394 std::get<InputPublisher::Finished>(*result);
3395 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3396 finish.consumeTime);
3397 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003398 if (shouldReportMetricsForConnection(*connection)) {
3399 const InputPublisher::Timeline& timeline =
3400 std::get<InputPublisher::Timeline>(*result);
3401 mLatencyTracker
3402 .trackGraphicsLatency(timeline.inputEventId,
3403 connection->inputChannel->getConnectionToken(),
3404 std::move(timeline.graphicsTimeline));
3405 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003406 }
3407 gotOne = true;
3408 }
3409 if (gotOne) {
3410 runCommandsLockedInterruptible();
3411 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 return 1;
3413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 }
3415
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003416 notify = status != DEAD_OBJECT || !connection->monitor;
3417 if (notify) {
3418 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3419 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3420 status);
3421 }
3422 } else {
3423 // Monitor channels are never explicitly unregistered.
3424 // We do it automatically when the remote endpoint is closed so don't warn about them.
3425 const bool stillHaveWindowHandle =
3426 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3427 notify = !connection->monitor && stillHaveWindowHandle;
3428 if (notify) {
3429 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3430 connection->getInputChannelName().c_str(), events);
3431 }
3432 }
3433
3434 // Remove the channel.
3435 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3436 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437}
3438
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003439void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003441 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003442 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
3444}
3445
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003447 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003448 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3449 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3450}
3451
3452void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3453 const CancelationOptions& options,
3454 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3455 for (const auto& it : monitorsByDisplay) {
3456 const std::vector<Monitor>& monitors = it.second;
3457 for (const Monitor& monitor : monitors) {
3458 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003459 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003460 }
3461}
3462
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003464 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003465 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003466 if (connection == nullptr) {
3467 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003469
3470 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471}
3472
3473void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3474 const sp<Connection>& connection, const CancelationOptions& options) {
3475 if (connection->status == Connection::STATUS_BROKEN) {
3476 return;
3477 }
3478
3479 nsecs_t currentTime = now();
3480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003481 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003482 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003484 if (cancelationEvents.empty()) {
3485 return;
3486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003488 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3489 "with reality: %s, mode=%d.",
3490 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3491 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003493
3494 InputTarget target;
3495 sp<InputWindowHandle> windowHandle =
3496 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3497 if (windowHandle != nullptr) {
3498 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003499 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003500 target.globalScaleFactor = windowInfo->globalScaleFactor;
3501 }
3502 target.inputChannel = connection->inputChannel;
3503 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3504
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003505 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003506 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003507 switch (cancelationEventEntry->type) {
3508 case EventEntry::Type::KEY: {
3509 logOutboundKeyDetails("cancel - ",
3510 static_cast<const KeyEntry&>(*cancelationEventEntry));
3511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003513 case EventEntry::Type::MOTION: {
3514 logOutboundMotionDetails("cancel - ",
3515 static_cast<const MotionEntry&>(*cancelationEventEntry));
3516 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003518 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003519 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3520 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003521 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003522 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003523 break;
3524 }
3525 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003526 case EventEntry::Type::DEVICE_RESET:
3527 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003528 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003529 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003530 break;
3531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003534 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3535 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003537
3538 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539}
3540
Svet Ganov5d3bc372020-01-26 23:11:07 -08003541void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3542 const sp<Connection>& connection) {
3543 if (connection->status == Connection::STATUS_BROKEN) {
3544 return;
3545 }
3546
3547 nsecs_t currentTime = now();
3548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003549 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003550 connection->inputState.synthesizePointerDownEvents(currentTime);
3551
3552 if (downEvents.empty()) {
3553 return;
3554 }
3555
3556#if DEBUG_OUTBOUND_EVENT_DETAILS
3557 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3558 connection->getInputChannelName().c_str(), downEvents.size());
3559#endif
3560
3561 InputTarget target;
3562 sp<InputWindowHandle> windowHandle =
3563 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3564 if (windowHandle != nullptr) {
3565 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003566 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003567 target.globalScaleFactor = windowInfo->globalScaleFactor;
3568 }
3569 target.inputChannel = connection->inputChannel;
3570 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3571
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003572 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003573 switch (downEventEntry->type) {
3574 case EventEntry::Type::MOTION: {
3575 logOutboundMotionDetails("down - ",
3576 static_cast<const MotionEntry&>(*downEventEntry));
3577 break;
3578 }
3579
3580 case EventEntry::Type::KEY:
3581 case EventEntry::Type::FOCUS:
3582 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003583 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003584 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003585 case EventEntry::Type::SENSOR:
3586 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003587 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003588 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003589 break;
3590 }
3591 }
3592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003593 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3594 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003595 }
3596
3597 startDispatchCycleLocked(currentTime, connection);
3598}
3599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003600std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3601 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 ALOG_ASSERT(pointerIds.value != 0);
3603
3604 uint32_t splitPointerIndexMap[MAX_POINTERS];
3605 PointerProperties splitPointerProperties[MAX_POINTERS];
3606 PointerCoords splitPointerCoords[MAX_POINTERS];
3607
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003608 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 uint32_t splitPointerCount = 0;
3610
3611 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003614 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 uint32_t pointerId = uint32_t(pointerProperties.id);
3616 if (pointerIds.hasBit(pointerId)) {
3617 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3618 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3619 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003620 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 splitPointerCount += 1;
3622 }
3623 }
3624
3625 if (splitPointerCount != pointerIds.count()) {
3626 // This is bad. We are missing some of the pointers that we expected to deliver.
3627 // Most likely this indicates that we received an ACTION_MOVE events that has
3628 // different pointer ids than we expected based on the previous ACTION_DOWN
3629 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3630 // in this way.
3631 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003632 "we expected there to be %d pointers. This probably means we received "
3633 "a broken sequence of pointer ids from the input device.",
3634 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003635 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 }
3637
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003638 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003640 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3641 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3643 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003644 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 uint32_t pointerId = uint32_t(pointerProperties.id);
3646 if (pointerIds.hasBit(pointerId)) {
3647 if (pointerIds.count() == 1) {
3648 // The first/last pointer went down/up.
3649 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003650 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003651 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3652 ? AMOTION_EVENT_ACTION_CANCEL
3653 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 } else {
3655 // A secondary pointer went down/up.
3656 uint32_t splitPointerIndex = 0;
3657 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3658 splitPointerIndex += 1;
3659 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 action = maskedAction |
3661 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663 } else {
3664 // An unrelated pointer changed.
3665 action = AMOTION_EVENT_ACTION_MOVE;
3666 }
3667 }
3668
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003669 int32_t newId = mIdGenerator.nextId();
3670 if (ATRACE_ENABLED()) {
3671 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3672 ") to MotionEvent(id=0x%" PRIx32 ").",
3673 originalMotionEntry.id, newId);
3674 ATRACE_NAME(message.c_str());
3675 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 std::unique_ptr<MotionEntry> splitMotionEntry =
3677 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3678 originalMotionEntry.deviceId, originalMotionEntry.source,
3679 originalMotionEntry.displayId,
3680 originalMotionEntry.policyFlags, action,
3681 originalMotionEntry.actionButton,
3682 originalMotionEntry.flags, originalMotionEntry.metaState,
3683 originalMotionEntry.buttonState,
3684 originalMotionEntry.classification,
3685 originalMotionEntry.edgeFlags,
3686 originalMotionEntry.xPrecision,
3687 originalMotionEntry.yPrecision,
3688 originalMotionEntry.xCursorPosition,
3689 originalMotionEntry.yCursorPosition,
3690 originalMotionEntry.downTime, splitPointerCount,
3691 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003693 if (originalMotionEntry.injectionState) {
3694 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 splitMotionEntry->injectionState->refCount += 1;
3696 }
3697
3698 return splitMotionEntry;
3699}
3700
3701void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3702#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003703 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704#endif
3705
3706 bool needWake;
3707 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003708 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003710 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3711 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3712 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 } // release lock
3714
3715 if (needWake) {
3716 mLooper->wake();
3717 }
3718}
3719
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003720/**
3721 * If one of the meta shortcuts is detected, process them here:
3722 * Meta + Backspace -> generate BACK
3723 * Meta + Enter -> generate HOME
3724 * This will potentially overwrite keyCode and metaState.
3725 */
3726void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003727 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003728 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3729 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3730 if (keyCode == AKEYCODE_DEL) {
3731 newKeyCode = AKEYCODE_BACK;
3732 } else if (keyCode == AKEYCODE_ENTER) {
3733 newKeyCode = AKEYCODE_HOME;
3734 }
3735 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003736 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003737 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003738 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003739 keyCode = newKeyCode;
3740 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3741 }
3742 } else if (action == AKEY_EVENT_ACTION_UP) {
3743 // In order to maintain a consistent stream of up and down events, check to see if the key
3744 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3745 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003746 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003747 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003748 auto replacementIt = mReplacedKeys.find(replacement);
3749 if (replacementIt != mReplacedKeys.end()) {
3750 keyCode = replacementIt->second;
3751 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003752 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3753 }
3754 }
3755}
3756
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3758#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003759 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3760 "policyFlags=0x%x, action=0x%x, "
3761 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3762 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3763 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3764 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765#endif
3766 if (!validateKeyEvent(args->action)) {
3767 return;
3768 }
3769
3770 uint32_t policyFlags = args->policyFlags;
3771 int32_t flags = args->flags;
3772 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003773 // InputDispatcher tracks and generates key repeats on behalf of
3774 // whatever notifies it, so repeatCount should always be set to 0
3775 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3777 policyFlags |= POLICY_FLAG_VIRTUAL;
3778 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 if (policyFlags & POLICY_FLAG_FUNCTION) {
3781 metaState |= AMETA_FUNCTION_ON;
3782 }
3783
3784 policyFlags |= POLICY_FLAG_TRUSTED;
3785
Michael Wright78f24442014-08-06 15:55:28 -07003786 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003787 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003788
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003790 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003791 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3792 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
Michael Wright2b3c3302018-03-02 17:19:13 +00003794 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003796 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3797 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003798 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 bool needWake;
3802 { // acquire lock
3803 mLock.lock();
3804
3805 if (shouldSendKeyToInputFilterLocked(args)) {
3806 mLock.unlock();
3807
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003808 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3810 return; // event was consumed by the filter
3811 }
3812
3813 mLock.lock();
3814 }
3815
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003816 std::unique_ptr<KeyEntry> newEntry =
3817 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3818 args->displayId, policyFlags, args->action, flags,
3819 keyCode, args->scanCode, metaState, repeatCount,
3820 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003822 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 mLock.unlock();
3824 } // release lock
3825
3826 if (needWake) {
3827 mLooper->wake();
3828 }
3829}
3830
3831bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3832 return mInputFilterEnabled;
3833}
3834
3835void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3836#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003837 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3838 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003839 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3840 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003841 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003842 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3843 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3844 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3845 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 for (uint32_t i = 0; i < args->pointerCount; i++) {
3847 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 "x=%f, y=%f, pressure=%f, size=%f, "
3849 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3850 "orientation=%f",
3851 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3852 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3853 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3854 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3855 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3856 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3857 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3858 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3859 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3860 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 }
3862#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003863 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3864 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 return;
3866 }
3867
3868 uint32_t policyFlags = args->policyFlags;
3869 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003870
3871 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003872 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003873 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3874 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877
3878 bool needWake;
3879 { // acquire lock
3880 mLock.lock();
3881
3882 if (shouldSendMotionToInputFilterLocked(args)) {
3883 mLock.unlock();
3884
3885 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003886 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003887 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3888 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003889 args->metaState, args->buttonState, args->classification, transform,
3890 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003891 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3892 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003893 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894
3895 policyFlags |= POLICY_FLAG_FILTERED;
3896 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3897 return; // event was consumed by the filter
3898 }
3899
3900 mLock.lock();
3901 }
3902
3903 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003904 std::unique_ptr<MotionEntry> newEntry =
3905 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3906 args->source, args->displayId, policyFlags,
3907 args->action, args->actionButton, args->flags,
3908 args->metaState, args->buttonState,
3909 args->classification, args->edgeFlags,
3910 args->xPrecision, args->yPrecision,
3911 args->xCursorPosition, args->yCursorPosition,
3912 args->downTime, args->pointerCount,
3913 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914
Siarhei Vishniakouf9cb2a72021-07-09 03:22:42 +00003915 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3916 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3917 !mInputFilterEnabled) {
3918 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3919 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3920 }
3921
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003922 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 mLock.unlock();
3924 } // release lock
3925
3926 if (needWake) {
3927 mLooper->wake();
3928 }
3929}
3930
Chris Yef59a2f42020-10-16 12:55:26 -07003931void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3932#if DEBUG_INBOUND_EVENT_DETAILS
3933 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3934 " sensorType=%s",
3935 args->id, args->eventTime, args->deviceId, args->source,
3936 NamedEnum::string(args->sensorType).c_str());
3937#endif
3938
3939 bool needWake;
3940 { // acquire lock
3941 mLock.lock();
3942
3943 // Just enqueue a new sensor event.
3944 std::unique_ptr<SensorEntry> newEntry =
3945 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3946 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3947 args->sensorType, args->accuracy,
3948 args->accuracyChanged, args->values);
3949
3950 needWake = enqueueInboundEventLocked(std::move(newEntry));
3951 mLock.unlock();
3952 } // release lock
3953
3954 if (needWake) {
3955 mLooper->wake();
3956 }
3957}
3958
Chris Yefb552902021-02-03 17:18:37 -08003959void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3960#if DEBUG_INBOUND_EVENT_DETAILS
3961 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3962 args->deviceId, args->isOn);
3963#endif
3964 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3965}
3966
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003968 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969}
3970
3971void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3972#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003973 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003974 "switchMask=0x%08x",
3975 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976#endif
3977
3978 uint32_t policyFlags = args->policyFlags;
3979 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981}
3982
3983void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3984#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003985 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3986 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987#endif
3988
3989 bool needWake;
3990 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003991 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003993 std::unique_ptr<DeviceResetEntry> newEntry =
3994 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3995 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 } // release lock
3997
3998 if (needWake) {
3999 mLooper->wake();
4000 }
4001}
4002
Prabir Pradhan7e186182020-11-10 13:56:45 -08004003void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
4004#if DEBUG_INBOUND_EVENT_DETAILS
4005 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhanf192a102021-08-06 14:01:18 +00004006 args->request.enable ? "true" : "false");
Prabir Pradhan7e186182020-11-10 13:56:45 -08004007#endif
4008
Prabir Pradhan99987712020-11-10 18:43:05 -08004009 bool needWake;
4010 { // acquire lock
4011 std::scoped_lock _l(mLock);
4012 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhanf192a102021-08-06 14:01:18 +00004013 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004014 needWake = enqueueInboundEventLocked(std::move(entry));
4015 } // release lock
4016
4017 if (needWake) {
4018 mLooper->wake();
4019 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004020}
4021
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004022InputEventInjectionResult InputDispatcher::injectInputEvent(
4023 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4024 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025#if DEBUG_INBOUND_EVENT_DETAILS
4026 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004027 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4028 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004030 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031
4032 policyFlags |= POLICY_FLAG_INJECTED;
4033 if (hasInjectionPermission(injectorPid, injectorUid)) {
4034 policyFlags |= POLICY_FLAG_TRUSTED;
4035 }
4036
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004037 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004038 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4039 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4040 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4041 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4042 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004043 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004044 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004045 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004046 }
4047
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004048 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004050 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004051 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4052 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004053 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004054 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004057 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004058 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4059 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4060 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004061 int32_t keyCode = incomingKey.getKeyCode();
4062 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004063 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004065 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004066 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004067 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4068 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4069 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4072 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004073 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074
4075 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4076 android::base::Timer t;
4077 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4078 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4079 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4080 std::to_string(t.duration().count()).c_str());
4081 }
4082 }
4083
4084 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004085 std::unique_ptr<KeyEntry> injectedEntry =
4086 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004087 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004088 incomingKey.getDisplayId(), policyFlags, action,
4089 flags, keyCode, incomingKey.getScanCode(), metaState,
4090 incomingKey.getRepeatCount(),
4091 incomingKey.getDownTime());
4092 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 }
4095
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004096 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004097 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4098 int32_t action = motionEvent.getAction();
4099 size_t pointerCount = motionEvent.getPointerCount();
4100 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4101 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004102 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004103 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004104 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004105 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106 }
4107
4108 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004109 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 android::base::Timer t;
4111 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4112 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4113 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4114 std::to_string(t.duration().count()).c_str());
4115 }
4116 }
4117
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004118 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4119 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4120 }
4121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004123 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4124 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004125 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004126 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4127 resolvedDeviceId, motionEvent.getSource(),
4128 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004129 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130 motionEvent.getButtonState(),
4131 motionEvent.getClassification(),
4132 motionEvent.getEdgeFlags(),
4133 motionEvent.getXPrecision(),
4134 motionEvent.getYPrecision(),
4135 motionEvent.getRawXCursorPosition(),
4136 motionEvent.getRawYCursorPosition(),
4137 motionEvent.getDownTime(), uint32_t(pointerCount),
4138 pointerProperties, samplePointerCoords,
4139 motionEvent.getXOffset(),
4140 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004141 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004142 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 sampleEventTimes += 1;
4144 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004145 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004146 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4147 resolvedDeviceId, motionEvent.getSource(),
4148 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004149 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004150 motionEvent.getMetaState(),
4151 motionEvent.getButtonState(),
4152 motionEvent.getClassification(),
4153 motionEvent.getEdgeFlags(),
4154 motionEvent.getXPrecision(),
4155 motionEvent.getYPrecision(),
4156 motionEvent.getRawXCursorPosition(),
4157 motionEvent.getRawYCursorPosition(),
4158 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004159 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004160 samplePointerCoords, motionEvent.getXOffset(),
4161 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004162 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 }
4164 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004168 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004169 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 }
4171
4172 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 injectionState->injectionIsAsync = true;
4175 }
4176
4177 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004178 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
4180 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004181 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004182 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004183 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 }
4185
4186 mLock.unlock();
4187
4188 if (needWake) {
4189 mLooper->wake();
4190 }
4191
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004192 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004194 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004196 if (syncMode == InputEventInjectionSync::NONE) {
4197 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 } else {
4199 for (;;) {
4200 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004201 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 break;
4203 }
4204
4205 nsecs_t remainingTimeout = endTime - now();
4206 if (remainingTimeout <= 0) {
4207#if DEBUG_INJECTION
4208 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004211 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 break;
4213 }
4214
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004215 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 }
4217
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004218 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4219 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 while (injectionState->pendingForegroundDispatches != 0) {
4221#if DEBUG_INJECTION
4222 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224#endif
4225 nsecs_t remainingTimeout = endTime - now();
4226 if (remainingTimeout <= 0) {
4227#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4229 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004231 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 break;
4233 }
4234
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004235 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237 }
4238 }
4239
4240 injectionState->release();
4241 } // release lock
4242
4243#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004244 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246#endif
4247
4248 return injectionResult;
4249}
4250
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004251std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004252 std::array<uint8_t, 32> calculatedHmac;
4253 std::unique_ptr<VerifiedInputEvent> result;
4254 switch (event.getType()) {
4255 case AINPUT_EVENT_TYPE_KEY: {
4256 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4257 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4258 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004259 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004260 break;
4261 }
4262 case AINPUT_EVENT_TYPE_MOTION: {
4263 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4264 VerifiedMotionEvent verifiedMotionEvent =
4265 verifiedMotionEventFromMotionEvent(motionEvent);
4266 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004267 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004268 break;
4269 }
4270 default: {
4271 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4272 return nullptr;
4273 }
4274 }
4275 if (calculatedHmac == INVALID_HMAC) {
4276 return nullptr;
4277 }
4278 if (calculatedHmac != event.getHmac()) {
4279 return nullptr;
4280 }
4281 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004282}
4283
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004285 return injectorUid == 0 ||
4286 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287}
4288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004289void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004290 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004291 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 if (injectionState) {
4293#if DEBUG_INJECTION
4294 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 "injectorPid=%d, injectorUid=%d",
4296 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297#endif
4298
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004299 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 // Log the outcome since the injector did not wait for the injection result.
4301 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004302 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004303 ALOGV("Asynchronous input event injection succeeded.");
4304 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 ALOGW("Asynchronous input event injection failed.");
4307 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004308 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004309 ALOGW("Asynchronous input event injection permission denied.");
4310 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004311 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 ALOGW("Asynchronous input event injection timed out.");
4313 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004314 case InputEventInjectionResult::PENDING:
4315 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4316 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
4318 }
4319
4320 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004321 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323}
4324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004325void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4326 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 if (injectionState) {
4328 injectionState->pendingForegroundDispatches += 1;
4329 }
4330}
4331
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004332void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4333 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 if (injectionState) {
4335 injectionState->pendingForegroundDispatches -= 1;
4336
4337 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004338 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 }
4340 }
4341}
4342
Vishnu Nairad321cd2020-08-20 16:40:21 -07004343const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004344 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004345 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4346 auto it = mWindowHandlesByDisplay.find(displayId);
4347 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004348}
4349
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004351 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004352 if (windowHandleToken == nullptr) {
4353 return nullptr;
4354 }
4355
Arthur Hungb92218b2018-08-14 12:00:21 +08004356 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004357 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004358 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004359 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004360 return windowHandle;
4361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 }
4363 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004364 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365}
4366
Vishnu Nairad321cd2020-08-20 16:40:21 -07004367sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4368 int displayId) const {
4369 if (windowHandleToken == nullptr) {
4370 return nullptr;
4371 }
4372
4373 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4374 if (windowHandle->getToken() == windowHandleToken) {
4375 return windowHandle;
4376 }
4377 }
4378 return nullptr;
4379}
4380
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004381sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4382 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004383 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004384 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004385 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004386 if (handle->getId() == windowHandle->getId() &&
4387 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004388 if (windowHandle->getInfo()->displayId != it.first) {
4389 ALOGE("Found window %s in display %" PRId32
4390 ", but it should belong to display %" PRId32,
4391 windowHandle->getName().c_str(), it.first,
4392 windowHandle->getInfo()->displayId);
4393 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004394 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 }
4397 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004398 return nullptr;
4399}
4400
4401sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4402 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4403 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404}
4405
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004406bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4407 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4408 const bool noInputChannel =
4409 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4410 if (connection != nullptr && noInputChannel) {
4411 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4412 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4413 return false;
4414 }
4415
4416 if (connection == nullptr) {
4417 if (!noInputChannel) {
4418 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4419 }
4420 return false;
4421 }
4422 if (!connection->responsive) {
4423 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4424 return false;
4425 }
4426 return true;
4427}
4428
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004429std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4430 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004431 auto connectionIt = mConnectionsByToken.find(token);
4432 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004433 return nullptr;
4434 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004435 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004436}
4437
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004438void InputDispatcher::updateWindowHandlesForDisplayLocked(
4439 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4440 if (inputWindowHandles.empty()) {
4441 // Remove all handles on a display if there are no windows left.
4442 mWindowHandlesByDisplay.erase(displayId);
4443 return;
4444 }
4445
4446 // Since we compare the pointer of input window handles across window updates, we need
4447 // to make sure the handle object for the same window stays unchanged across updates.
4448 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004449 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004450 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004451 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004452 }
4453
4454 std::vector<sp<InputWindowHandle>> newHandles;
4455 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4456 if (!handle->updateInfo()) {
4457 // handle no longer valid
4458 continue;
4459 }
4460
4461 const InputWindowInfo* info = handle->getInfo();
4462 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4463 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4464 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004465 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4466 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4467 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004468 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004469 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004470 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004471 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004472 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004473 }
4474
4475 if (info->displayId != displayId) {
4476 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4477 handle->getName().c_str(), displayId, info->displayId);
4478 continue;
4479 }
4480
Robert Carredd13602020-04-13 17:24:34 -07004481 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4482 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004483 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004484 oldHandle->updateFrom(handle);
4485 newHandles.push_back(oldHandle);
4486 } else {
4487 newHandles.push_back(handle);
4488 }
4489 }
4490
4491 // Insert or replace
4492 mWindowHandlesByDisplay[displayId] = newHandles;
4493}
4494
Arthur Hung72d8dc32020-03-28 00:48:39 +00004495void InputDispatcher::setInputWindows(
4496 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4497 { // acquire lock
4498 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004499 for (const auto& [displayId, handles] : handlesPerDisplay) {
4500 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004501 }
4502 }
4503 // Wake up poll loop since it may need to make new input dispatching choices.
4504 mLooper->wake();
4505}
4506
Arthur Hungb92218b2018-08-14 12:00:21 +08004507/**
4508 * Called from InputManagerService, update window handle list by displayId that can receive input.
4509 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4510 * If set an empty list, remove all handles from the specific display.
4511 * For focused handle, check if need to change and send a cancel event to previous one.
4512 * For removed handle, check if need to send a cancel event if already in touch.
4513 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004514void InputDispatcher::setInputWindowsLocked(
4515 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004516 if (DEBUG_FOCUS) {
4517 std::string windowList;
4518 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4519 windowList += iwh->getName() + " ";
4520 }
4521 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004524 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4525 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4526 const bool noInputWindow =
4527 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4528 if (noInputWindow && window->getToken() != nullptr) {
4529 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4530 window->getName().c_str());
4531 window->releaseChannel();
4532 }
4533 }
4534
Arthur Hung72d8dc32020-03-28 00:48:39 +00004535 // Copy old handles for release if they are no longer present.
4536 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004538 // Save the old windows' orientation by ID before it gets updated.
4539 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4540 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4541 oldWindowOrientations.emplace(handle->getId(),
4542 handle->getInfo()->transform.getOrientation());
4543 }
4544
Arthur Hung72d8dc32020-03-28 00:48:39 +00004545 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004546
Vishnu Nair958da932020-08-21 17:12:37 -07004547 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4548 if (mLastHoverWindowHandle &&
4549 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4550 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004551 mLastHoverWindowHandle = nullptr;
4552 }
4553
Vishnu Nairc519ff72021-01-21 08:23:08 -08004554 std::optional<FocusResolver::FocusChanges> changes =
4555 mFocusResolver.setInputWindows(displayId, windowHandles);
4556 if (changes) {
4557 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004560 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4561 mTouchStatesByDisplay.find(displayId);
4562 if (stateIt != mTouchStatesByDisplay.end()) {
4563 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004564 for (size_t i = 0; i < state.windows.size();) {
4565 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004566 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004567 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004568 ALOGD("Touched window was removed: %s in display %" PRId32,
4569 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004570 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004571 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004572 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4573 if (touchedInputChannel != nullptr) {
4574 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4575 "touched window was removed");
4576 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004578 state.windows.erase(state.windows.begin() + i);
4579 } else {
4580 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 }
4582 }
arthurhungb89ccb02020-12-30 16:19:01 +08004583
arthurhung6d4bed92021-03-17 11:59:33 +08004584 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004585 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004586 if (mDragState &&
4587 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004588 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004589 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004590 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004591 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004592
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004593 if (isPerWindowInputRotationEnabled()) {
4594 // Determine if the orientation of any of the input windows have changed, and cancel all
4595 // pointer events if necessary.
4596 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4597 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4598 if (newWindowHandle != nullptr &&
4599 newWindowHandle->getInfo()->transform.getOrientation() !=
4600 oldWindowOrientations[oldWindowHandle->getId()]) {
4601 std::shared_ptr<InputChannel> inputChannel =
4602 getInputChannelLocked(newWindowHandle->getToken());
4603 if (inputChannel != nullptr) {
4604 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4605 "touched window's orientation changed");
4606 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4607 }
4608 }
4609 }
4610 }
4611
Arthur Hung72d8dc32020-03-28 00:48:39 +00004612 // Release information for windows that are no longer present.
4613 // This ensures that unused input channels are released promptly.
4614 // Otherwise, they might stick around until the window handle is destroyed
4615 // which might not happen until the next GC.
4616 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004617 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004618 if (DEBUG_FOCUS) {
4619 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004620 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004621 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004622 // To avoid making too many calls into the compat framework, only
4623 // check for window flags when windows are going away.
4624 // TODO(b/157929241) : delete this. This is only needed temporarily
4625 // in order to gather some data about the flag usage
4626 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4627 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4628 oldWindowHandle->getName().c_str());
4629 if (mCompatService != nullptr) {
4630 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4631 oldWindowHandle->getInfo()->ownerUid);
4632 }
4633 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004634 }
chaviw291d88a2019-02-14 10:33:58 -08004635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636}
4637
4638void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004639 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004640 if (DEBUG_FOCUS) {
4641 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4642 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4643 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004644 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004645 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004646 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 } // release lock
4648
4649 // Wake up poll loop since it may need to make new input dispatching choices.
4650 mLooper->wake();
4651}
4652
Vishnu Nair599f1412021-06-21 10:39:58 -07004653void InputDispatcher::setFocusedApplicationLocked(
4654 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4655 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4656 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4657
4658 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4659 return; // This application is already focused. No need to wake up or change anything.
4660 }
4661
4662 // Set the new application handle.
4663 if (inputApplicationHandle != nullptr) {
4664 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4665 } else {
4666 mFocusedApplicationHandlesByDisplay.erase(displayId);
4667 }
4668
4669 // No matter what the old focused application was, stop waiting on it because it is
4670 // no longer focused.
4671 resetNoFocusedWindowTimeoutLocked();
4672}
4673
Tiger Huang721e26f2018-07-24 22:26:19 +08004674/**
4675 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4676 * the display not specified.
4677 *
4678 * We track any unreleased events for each window. If a window loses the ability to receive the
4679 * released event, we will send a cancel event to it. So when the focused display is changed, we
4680 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4681 * display. The display-specified events won't be affected.
4682 */
4683void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004684 if (DEBUG_FOCUS) {
4685 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4686 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004687 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004688 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004689
4690 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004691 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004692 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004693 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004694 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004695 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004696 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004697 CancelationOptions
4698 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4699 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004700 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004701 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4702 }
4703 }
4704 mFocusedDisplayId = displayId;
4705
Chris Ye3c2d6f52020-08-09 10:39:48 -07004706 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004707 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004708 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004709
Vishnu Nairad321cd2020-08-20 16:40:21 -07004710 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004711 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004712 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004713 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004714 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004715 }
4716 }
4717 }
4718
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004719 if (DEBUG_FOCUS) {
4720 logDispatchStateLocked();
4721 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004722 } // release lock
4723
4724 // Wake up poll loop since it may need to make new input dispatching choices.
4725 mLooper->wake();
4726}
4727
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004729 if (DEBUG_FOCUS) {
4730 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732
4733 bool changed;
4734 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004735 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
4737 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4738 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004739 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 }
4741
4742 if (mDispatchEnabled && !enabled) {
4743 resetAndDropEverythingLocked("dispatcher is being disabled");
4744 }
4745
4746 mDispatchEnabled = enabled;
4747 mDispatchFrozen = frozen;
4748 changed = true;
4749 } else {
4750 changed = false;
4751 }
4752
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004753 if (DEBUG_FOCUS) {
4754 logDispatchStateLocked();
4755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 } // release lock
4757
4758 if (changed) {
4759 // Wake up poll loop since it may need to make new input dispatching choices.
4760 mLooper->wake();
4761 }
4762}
4763
4764void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004765 if (DEBUG_FOCUS) {
4766 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768
4769 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004770 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771
4772 if (mInputFilterEnabled == enabled) {
4773 return;
4774 }
4775
4776 mInputFilterEnabled = enabled;
4777 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4778 } // release lock
4779
4780 // Wake up poll loop since there might be work to do to drop everything.
4781 mLooper->wake();
4782}
4783
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004784void InputDispatcher::setInTouchMode(bool inTouchMode) {
4785 std::scoped_lock lock(mLock);
4786 mInTouchMode = inTouchMode;
4787}
4788
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004789void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4790 if (opacity < 0 || opacity > 1) {
4791 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4792 return;
4793 }
4794
4795 std::scoped_lock lock(mLock);
4796 mMaximumObscuringOpacityForTouch = opacity;
4797}
4798
4799void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4800 std::scoped_lock lock(mLock);
4801 mBlockUntrustedTouchesMode = mode;
4802}
4803
arthurhungb89ccb02020-12-30 16:19:01 +08004804bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4805 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004806 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004807 if (DEBUG_FOCUS) {
4808 ALOGD("Trivial transfer to same window.");
4809 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004810 return true;
4811 }
4812
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004814 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815
chaviwfbe5d9c2018-12-26 12:23:37 -08004816 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4817 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004818 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004819 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 return false;
4821 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004822 if (DEBUG_FOCUS) {
4823 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4824 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004827 if (DEBUG_FOCUS) {
4828 ALOGD("Cannot transfer focus because windows are on different displays.");
4829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 return false;
4831 }
4832
4833 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004834 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4835 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004836 for (size_t i = 0; i < state.windows.size(); i++) {
4837 const TouchedWindow& touchedWindow = state.windows[i];
4838 if (touchedWindow.windowHandle == fromWindowHandle) {
4839 int32_t oldTargetFlags = touchedWindow.targetFlags;
4840 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004842 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 int32_t newTargetFlags = oldTargetFlags &
4845 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4846 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004847 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
arthurhungb89ccb02020-12-30 16:19:01 +08004849 // Store the dragging window.
4850 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004851 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004852 }
4853
Jeff Brownf086ddb2014-02-11 14:28:48 -08004854 found = true;
4855 goto Found;
4856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004859 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004861 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004862 if (DEBUG_FOCUS) {
4863 ALOGD("Focus transfer failed because from window did not have focus.");
4864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 return false;
4866 }
4867
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004868 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4869 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004870 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004871 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004872 CancelationOptions
4873 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4874 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004876 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
4878
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004879 if (DEBUG_FOCUS) {
4880 logDispatchStateLocked();
4881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 } // release lock
4883
4884 // Wake up poll loop since it may need to make new input dispatching choices.
4885 mLooper->wake();
4886 return true;
4887}
4888
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004889// Binder call
4890bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4891 sp<IBinder> fromToken;
4892 { // acquire lock
4893 std::scoped_lock _l(mLock);
4894
4895 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4896 if (toWindowHandle == nullptr) {
4897 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4898 return false;
4899 }
4900
4901 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4902
4903 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4904 if (touchStateIt == mTouchStatesByDisplay.end()) {
4905 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4906 displayId);
4907 return false;
4908 }
4909
4910 TouchState& state = touchStateIt->second;
4911 if (state.windows.size() != 1) {
4912 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4913 state.windows.size());
4914 return false;
4915 }
4916 const TouchedWindow& touchedWindow = state.windows[0];
4917 fromToken = touchedWindow.windowHandle->getToken();
4918 } // release lock
4919
4920 return transferTouchFocus(fromToken, destChannelToken);
4921}
4922
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004924 if (DEBUG_FOCUS) {
4925 ALOGD("Resetting and dropping all events (%s).", reason);
4926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927
4928 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4929 synthesizeCancelationEventsForAllConnectionsLocked(options);
4930
4931 resetKeyRepeatLocked();
4932 releasePendingEventLocked();
4933 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004936 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004937 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004939 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940}
4941
4942void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004943 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 dumpDispatchStateLocked(dump);
4945
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004946 std::istringstream stream(dump);
4947 std::string line;
4948
4949 while (std::getline(stream, line, '\n')) {
4950 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
4952}
4953
Prabir Pradhan99987712020-11-10 18:43:05 -08004954std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4955 std::string dump;
4956
Prabir Pradhanf192a102021-08-06 14:01:18 +00004957 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
4958 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08004959
4960 std::string windowName = "None";
4961 if (mWindowTokenWithPointerCapture) {
4962 const sp<InputWindowHandle> captureWindowHandle =
4963 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4964 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4965 : "token has capture without window";
4966 }
Prabir Pradhanf192a102021-08-06 14:01:18 +00004967 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08004968
4969 return dump;
4970}
4971
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004972void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004973 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4974 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4975 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004976 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977
Tiger Huang721e26f2018-07-24 22:26:19 +08004978 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4979 dump += StringPrintf(INDENT "FocusedApplications:\n");
4980 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4981 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004982 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004983 const std::chrono::duration timeout =
4984 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004985 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004986 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004987 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004990 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004992
Vishnu Nairc519ff72021-01-21 08:23:08 -08004993 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004994 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004996 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004997 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004998 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4999 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005000 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005001 state.displayId, toString(state.down), toString(state.split),
5002 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005003 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005004 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005005 for (size_t i = 0; i < state.windows.size(); i++) {
5006 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 dump += StringPrintf(INDENT4
5008 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5009 i, touchedWindow.windowHandle->getName().c_str(),
5010 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005011 }
5012 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005013 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005014 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005015 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005016 dump += INDENT3 "Portal windows:\n";
5017 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005018 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5020 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005021 }
5022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023 }
5024 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005025 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026 }
5027
arthurhung6d4bed92021-03-17 11:59:33 +08005028 if (mDragState) {
5029 dump += StringPrintf(INDENT "DragState:\n");
5030 mDragState->dump(dump, INDENT2);
5031 }
5032
Arthur Hungb92218b2018-08-14 12:00:21 +08005033 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005034 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005035 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005036 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005037 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005038 dump += INDENT2 "Windows:\n";
5039 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005040 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08005041 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005043 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005044 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005045 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005046 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005047 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005048 "applicationInfo.name=%s, "
5049 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005050 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005051 i, windowInfo->name.c_str(), windowInfo->id,
5052 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005053 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005054 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005055 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005056 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005057 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005058 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005059 windowInfo->frameLeft, windowInfo->frameTop,
5060 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005061 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005062 windowInfo->applicationInfo.name.c_str(),
5063 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005064 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005065 dump += StringPrintf(", inputFeatures=%s",
5066 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005067 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005068 "ms, trustedOverlay=%s, hasToken=%s, "
5069 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005070 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005071 millis(windowInfo->dispatchingTimeout),
5072 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005073 toString(windowInfo->token != nullptr),
5074 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005075 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005076 }
5077 } else {
5078 dump += INDENT2 "Windows: <none>\n";
5079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 }
5081 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005082 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083 }
5084
Michael Wright3dd60e22019-03-27 22:06:44 +00005085 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005086 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005087 const std::vector<Monitor>& monitors = it.second;
5088 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5089 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005090 }
5091 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005092 const std::vector<Monitor>& monitors = it.second;
5093 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5094 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005097 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 }
5099
5100 nsecs_t currentTime = now();
5101
5102 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005103 if (!mRecentQueue.empty()) {
5104 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005105 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005107 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005108 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 }
5110 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005111 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113
5114 // Dump event currently being dispatched.
5115 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005116 dump += INDENT "PendingEvent:\n";
5117 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005118 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005119 dump += StringPrintf(", age=%" PRId64 "ms\n",
5120 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005122 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 }
5124
5125 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005126 if (!mInboundQueue.empty()) {
5127 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005128 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005129 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005130 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005131 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 }
5133 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005134 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 }
5136
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005137 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005138 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005139 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5140 const KeyReplacement& replacement = pair.first;
5141 int32_t newKeyCode = pair.second;
5142 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005143 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005144 }
5145 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005146 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005147 }
5148
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005149 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005150 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005151 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005152 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005153 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005154 connection->inputChannel->getFd().get(),
5155 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005156 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005157 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005159 if (!connection->outboundQueue.empty()) {
5160 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5161 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005162 dump += dumpQueue(connection->outboundQueue, currentTime);
5163
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005168 if (!connection->waitQueue.empty()) {
5169 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5170 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005171 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005173 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 }
5175 }
5176 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005177 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 }
5179
5180 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005181 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5182 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005184 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 }
5186
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005187 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005188 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5189 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5190 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005191 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005192 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193}
5194
Michael Wright3dd60e22019-03-27 22:06:44 +00005195void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5196 const size_t numMonitors = monitors.size();
5197 for (size_t i = 0; i < numMonitors; i++) {
5198 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005199 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005200 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5201 dump += "\n";
5202 }
5203}
5204
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005205class LooperEventCallback : public LooperCallback {
5206public:
5207 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5208 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5209
5210private:
5211 std::function<int(int events)> mCallback;
5212};
5213
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005214Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005215#if DEBUG_CHANNEL_CREATION
5216 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217#endif
5218
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005219 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005220 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005221 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005222
5223 if (result) {
5224 return base::Error(result) << "Failed to open input channel pair with name " << name;
5225 }
5226
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005228 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005229 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005230 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005231 sp<Connection> connection =
5232 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005234 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5235 ALOGE("Created a new connection, but the token %p is already known", token.get());
5236 }
5237 mConnectionsByToken.emplace(token, connection);
5238
5239 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5240 this, std::placeholders::_1, token);
5241
5242 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 } // release lock
5244
5245 // Wake the looper because some connections have changed.
5246 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005247 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248}
5249
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005250Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5251 bool isGestureMonitor,
5252 const std::string& name,
5253 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005254 std::shared_ptr<InputChannel> serverChannel;
5255 std::unique_ptr<InputChannel> clientChannel;
5256 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5257 if (result) {
5258 return base::Error(result) << "Failed to open input channel pair with name " << name;
5259 }
5260
Michael Wright3dd60e22019-03-27 22:06:44 +00005261 { // acquire lock
5262 std::scoped_lock _l(mLock);
5263
5264 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005265 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5266 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005267 }
5268
Garfield Tan15601662020-09-22 15:32:38 -07005269 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005270 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005271 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272
5273 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5274 ALOGE("Created a new connection, but the token %p is already known", token.get());
5275 }
5276 mConnectionsByToken.emplace(token, connection);
5277 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5278 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005279
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005280 auto& monitorsByDisplay =
5281 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005282 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005283
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005284 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005285 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5286 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005287 }
Garfield Tan15601662020-09-22 15:32:38 -07005288
Michael Wright3dd60e22019-03-27 22:06:44 +00005289 // Wake the looper because some connections have changed.
5290 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005291 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005292}
5293
Garfield Tan15601662020-09-22 15:32:38 -07005294status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005296 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297
Garfield Tan15601662020-09-22 15:32:38 -07005298 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 if (status) {
5300 return status;
5301 }
5302 } // release lock
5303
5304 // Wake the poll loop because removing the connection may have changed the current
5305 // synchronization state.
5306 mLooper->wake();
5307 return OK;
5308}
5309
Garfield Tan15601662020-09-22 15:32:38 -07005310status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5311 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005312 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005313 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005314 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 return BAD_VALUE;
5316 }
5317
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005318 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005319
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005321 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 }
5323
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005324 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325
5326 nsecs_t currentTime = now();
5327 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5328
5329 connection->status = Connection::STATUS_ZOMBIE;
5330 return OK;
5331}
5332
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005333void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5334 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5335 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005336}
5337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005338void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005339 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005341 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005342 std::vector<Monitor>& monitors = it->second;
5343 const size_t numMonitors = monitors.size();
5344 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005345 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005346 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5347 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005348 monitors.erase(monitors.begin() + i);
5349 break;
5350 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005351 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005352 if (monitors.empty()) {
5353 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005354 } else {
5355 ++it;
5356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 }
5358}
5359
Michael Wright3dd60e22019-03-27 22:06:44 +00005360status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5361 { // acquire lock
5362 std::scoped_lock _l(mLock);
5363 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5364
5365 if (!foundDisplayId) {
5366 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5367 return BAD_VALUE;
5368 }
5369 int32_t displayId = foundDisplayId.value();
5370
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005371 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5372 mTouchStatesByDisplay.find(displayId);
5373 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005374 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5375 return BAD_VALUE;
5376 }
5377
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005378 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005379 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005380 std::optional<int32_t> foundDeviceId;
5381 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005382 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005383 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005384 foundDeviceId = state.deviceId;
5385 }
5386 }
5387 if (!foundDeviceId || !state.down) {
5388 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005389 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005390 return BAD_VALUE;
5391 }
5392 int32_t deviceId = foundDeviceId.value();
5393
5394 // Send cancel events to all the input channels we're stealing from.
5395 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005396 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005397 options.deviceId = deviceId;
5398 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005399 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005400 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005401 std::shared_ptr<InputChannel> channel =
5402 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005403 if (channel != nullptr) {
5404 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005405 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005406 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005407 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005408 canceledWindows += "]";
5409 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5410 canceledWindows.c_str());
5411
Michael Wright3dd60e22019-03-27 22:06:44 +00005412 // Then clear the current touch state so we stop dispatching to them as well.
5413 state.filterNonMonitors();
5414 }
5415 return OK;
5416}
5417
Prabir Pradhan99987712020-11-10 18:43:05 -08005418void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5419 { // acquire lock
5420 std::scoped_lock _l(mLock);
5421 if (DEBUG_FOCUS) {
5422 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5423 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5424 windowHandle != nullptr ? windowHandle->getName().c_str()
5425 : "token without window");
5426 }
5427
Vishnu Nairc519ff72021-01-21 08:23:08 -08005428 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005429 if (focusedToken != windowToken) {
5430 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5431 enabled ? "enable" : "disable");
5432 return;
5433 }
5434
Prabir Pradhanf192a102021-08-06 14:01:18 +00005435 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005436 ALOGW("Ignoring request to %s Pointer Capture: "
5437 "window has %s requested pointer capture.",
5438 enabled ? "enable" : "disable", enabled ? "already" : "not");
5439 return;
5440 }
5441
Prabir Pradhan99987712020-11-10 18:43:05 -08005442 setPointerCaptureLocked(enabled);
5443 } // release lock
5444
5445 // Wake the thread to process command entries.
5446 mLooper->wake();
5447}
5448
Michael Wright3dd60e22019-03-27 22:06:44 +00005449std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5450 const sp<IBinder>& token) {
5451 for (const auto& it : mGestureMonitorsByDisplay) {
5452 const std::vector<Monitor>& monitors = it.second;
5453 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005454 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005455 return it.first;
5456 }
5457 }
5458 }
5459 return std::nullopt;
5460}
5461
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005462std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5463 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5464 if (gesturePid.has_value()) {
5465 return gesturePid;
5466 }
5467 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5468}
5469
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005470sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005471 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005472 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005473 }
5474
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005475 for (const auto& [token, connection] : mConnectionsByToken) {
5476 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005477 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479 }
Robert Carr4e670e52018-08-15 13:26:12 -07005480
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005481 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482}
5483
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005484std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5485 sp<Connection> connection = getConnectionLocked(connectionToken);
5486 if (connection == nullptr) {
5487 return "<nullptr>";
5488 }
5489 return connection->getInputChannelName();
5490}
5491
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005492void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005493 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005494 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005495}
5496
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005497void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5498 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005499 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005500 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5501 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 commandEntry->connection = connection;
5503 commandEntry->eventTime = currentTime;
5504 commandEntry->seq = seq;
5505 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005506 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005507 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508}
5509
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005510void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5511 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005513 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005515 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5516 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005518 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519}
5520
Vishnu Nairad321cd2020-08-20 16:40:21 -07005521void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5522 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005523 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5524 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005525 commandEntry->oldToken = oldToken;
5526 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005527 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005528}
5529
arthurhungf452d0b2021-01-06 00:19:52 +08005530void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5531 std::unique_ptr<CommandEntry> commandEntry =
5532 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5533 commandEntry->newToken = token;
5534 commandEntry->x = x;
5535 commandEntry->y = y;
5536 postCommandLocked(std::move(commandEntry));
5537}
5538
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005539void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5540 if (connection == nullptr) {
5541 LOG_ALWAYS_FATAL("Caller must check for nullness");
5542 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005543 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5544 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005545 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005546 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005547 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005548 return;
5549 }
5550 /**
5551 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5552 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5553 * has changed. This could cause newer entries to time out before the already dispatched
5554 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5555 * processes the events linearly. So providing information about the oldest entry seems to be
5556 * most useful.
5557 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005558 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005559 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5560 std::string reason =
5561 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005562 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005563 ns2ms(currentWait),
5564 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005565 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005566 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005567
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005568 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5569
5570 // Stop waking up for events on this connection, it is already unresponsive
5571 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005572}
5573
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005574void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5575 std::string reason =
5576 StringPrintf("%s does not have a focused window", application->getName().c_str());
5577 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005578
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005579 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5580 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5581 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005582 postCommandLocked(std::move(commandEntry));
5583}
5584
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005585void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5586 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5587 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5588 commandEntry->obscuringPackage = obscuringPackage;
5589 postCommandLocked(std::move(commandEntry));
5590}
5591
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005592void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5593 const std::string& reason) {
5594 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5595 updateLastAnrStateLocked(windowLabel, reason);
5596}
5597
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005598void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5599 const std::string& reason) {
5600 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005601 updateLastAnrStateLocked(windowLabel, reason);
5602}
5603
5604void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5605 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005607 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608 struct tm tm;
5609 localtime_r(&t, &tm);
5610 char timestr[64];
5611 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005612 mLastAnrState.clear();
5613 mLastAnrState += INDENT "ANR:\n";
5614 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005615 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5616 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005617 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618}
5619
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005620void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 mLock.unlock();
5622
5623 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5624
5625 mLock.lock();
5626}
5627
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005628void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 sp<Connection> connection = commandEntry->connection;
5630
5631 if (connection->status != Connection::STATUS_ZOMBIE) {
5632 mLock.unlock();
5633
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005634 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635
5636 mLock.lock();
5637 }
5638}
5639
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005640void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005641 sp<IBinder> oldToken = commandEntry->oldToken;
5642 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005643 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005644 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005645 mLock.lock();
5646}
5647
arthurhungf452d0b2021-01-06 00:19:52 +08005648void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5649 sp<IBinder> newToken = commandEntry->newToken;
5650 mLock.unlock();
5651 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5652 mLock.lock();
5653}
5654
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005655void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005657
5658 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5659
5660 mLock.lock();
5661}
5662
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005663void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005664 mLock.unlock();
5665
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005666 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667
5668 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005669}
5670
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005671void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005672 mLock.unlock();
5673
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005674 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5675
5676 mLock.lock();
5677}
5678
5679void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5680 mLock.unlock();
5681
5682 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5683
5684 mLock.lock();
5685}
5686
5687void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5688 mLock.unlock();
5689
5690 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005691
5692 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005693}
5694
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005695void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5696 mLock.unlock();
5697
5698 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5699
5700 mLock.lock();
5701}
5702
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5704 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005705 KeyEntry& entry = *(commandEntry->keyEntry);
5706 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707
5708 mLock.unlock();
5709
Michael Wright2b3c3302018-03-02 17:19:13 +00005710 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005711 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005712 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005713 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5714 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005715 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717
5718 mLock.lock();
5719
5720 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005721 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005723 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005725 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5726 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728}
5729
chaviwfd6d3512019-03-25 13:23:49 -07005730void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5731 mLock.unlock();
5732 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5733 mLock.lock();
5734}
5735
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005736/**
5737 * Connection is responsive if it has no events in the waitQueue that are older than the
5738 * current time.
5739 */
5740static bool isConnectionResponsive(const Connection& connection) {
5741 const nsecs_t currentTime = now();
5742 for (const DispatchEntry* entry : connection.waitQueue) {
5743 if (entry->timeoutTime < currentTime) {
5744 return false;
5745 }
5746 }
5747 return true;
5748}
5749
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005750void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005752 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005754 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755
5756 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005757 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005758 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005759 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005761 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005762 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005763 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005764 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5765 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005766 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005767 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5768 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5769 connection->inputChannel->getConnectionToken(),
5770 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5771 finishTime);
5772 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005773
5774 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005775 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005776 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005777 restartEvent =
5778 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005779 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005780 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005781 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5782 handled);
5783 } else {
5784 restartEvent = false;
5785 }
5786
5787 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005788 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005789 // contents of the wait queue to have been drained, so we need to double-check
5790 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005791 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5792 if (dispatchEntryIt != connection->waitQueue.end()) {
5793 dispatchEntry = *dispatchEntryIt;
5794 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005795 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5796 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005797 if (!connection->responsive) {
5798 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005799 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005800 // The connection was unresponsive, and now it's responsive.
5801 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005802 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005803 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005804 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005805 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005806 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005807 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005808 } else {
5809 releaseDispatchEntry(dispatchEntry);
5810 }
5811 }
5812
5813 // Start the next dispatch cycle for this connection.
5814 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815}
5816
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005817void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5818 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5819 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5820 monitorUnresponsiveCommand->pid = pid;
5821 monitorUnresponsiveCommand->reason = std::move(reason);
5822 postCommandLocked(std::move(monitorUnresponsiveCommand));
5823}
5824
5825void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5826 std::string reason) {
5827 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5828 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5829 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5830 windowUnresponsiveCommand->reason = std::move(reason);
5831 postCommandLocked(std::move(windowUnresponsiveCommand));
5832}
5833
5834void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5835 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5836 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5837 monitorResponsiveCommand->pid = pid;
5838 postCommandLocked(std::move(monitorResponsiveCommand));
5839}
5840
5841void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5842 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5843 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5844 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5845 postCommandLocked(std::move(windowResponsiveCommand));
5846}
5847
5848/**
5849 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5850 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5851 * command entry to the command queue.
5852 */
5853void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5854 std::string reason) {
5855 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5856 if (connection.monitor) {
5857 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5858 reason.c_str());
5859 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5860 if (!pid.has_value()) {
5861 ALOGE("Could not find unresponsive monitor for connection %s",
5862 connection.inputChannel->getName().c_str());
5863 return;
5864 }
5865 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5866 return;
5867 }
5868 // If not a monitor, must be a window
5869 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5870 reason.c_str());
5871 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5872}
5873
5874/**
5875 * Tell the policy that a connection has become responsive so that it can stop ANR.
5876 */
5877void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5878 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5879 if (connection.monitor) {
5880 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5881 if (!pid.has_value()) {
5882 ALOGE("Could not find responsive monitor for connection %s",
5883 connection.inputChannel->getName().c_str());
5884 return;
5885 }
5886 sendMonitorResponsiveCommandLocked(pid.value());
5887 return;
5888 }
5889 // If not a monitor, must be a window
5890 sendWindowResponsiveCommandLocked(connectionToken);
5891}
5892
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005894 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005895 KeyEntry& keyEntry, bool handled) {
5896 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005897 if (!handled) {
5898 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005899 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005900 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005901 return false;
5902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005904 // Get the fallback key state.
5905 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005906 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005907 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005908 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005909 connection->inputState.removeFallbackKey(originalKeyCode);
5910 }
5911
5912 if (handled || !dispatchEntry->hasForegroundTarget()) {
5913 // If the application handles the original key for which we previously
5914 // generated a fallback or if the window is not a foreground window,
5915 // then cancel the associated fallback key, if any.
5916 if (fallbackKeyCode != -1) {
5917 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005919 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005920 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005921 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005923 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005924 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925
5926 mLock.unlock();
5927
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005928 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005929 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930
5931 mLock.lock();
5932
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005933 // Cancel the fallback key.
5934 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005936 "application handled the original non-fallback key "
5937 "or is no longer a foreground target, "
5938 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 options.keyCode = fallbackKeyCode;
5940 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005942 connection->inputState.removeFallbackKey(originalKeyCode);
5943 }
5944 } else {
5945 // If the application did not handle a non-fallback key, first check
5946 // that we are in a good state to perform unhandled key event processing
5947 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005948 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005949 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005951 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005952 "since this is not an initial down. "
5953 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005954 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956 return false;
5957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959 // Dispatch the unhandled key to the policy.
5960#if DEBUG_OUTBOUND_EVENT_DETAILS
5961 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005962 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005963 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005964#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005965 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005966
5967 mLock.unlock();
5968
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005969 bool fallback =
5970 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005971 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005972
5973 mLock.lock();
5974
5975 if (connection->status != Connection::STATUS_NORMAL) {
5976 connection->inputState.removeFallbackKey(originalKeyCode);
5977 return false;
5978 }
5979
5980 // Latch the fallback keycode for this key on an initial down.
5981 // The fallback keycode cannot change at any other point in the lifecycle.
5982 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005984 fallbackKeyCode = event.getKeyCode();
5985 } else {
5986 fallbackKeyCode = AKEYCODE_UNKNOWN;
5987 }
5988 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5989 }
5990
5991 ALOG_ASSERT(fallbackKeyCode != -1);
5992
5993 // Cancel the fallback key if the policy decides not to send it anymore.
5994 // We will continue to dispatch the key to the policy but we will no
5995 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005996 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5997 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005998#if DEBUG_OUTBOUND_EVENT_DETAILS
5999 if (fallback) {
6000 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006001 "as a fallback for %d, but on the DOWN it had requested "
6002 "to send %d instead. Fallback canceled.",
6003 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006004 } else {
6005 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006006 "but on the DOWN it had requested to send %d. "
6007 "Fallback canceled.",
6008 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006009 }
6010#endif
6011
6012 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6013 "canceling fallback, policy no longer desires it");
6014 options.keyCode = fallbackKeyCode;
6015 synthesizeCancelationEventsForConnectionLocked(connection, options);
6016
6017 fallback = false;
6018 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006019 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006020 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006021 }
6022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006023
6024#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006025 {
6026 std::string msg;
6027 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6028 connection->inputState.getFallbackKeys();
6029 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006030 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006032 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006033 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006034 }
6035#endif
6036
6037 if (fallback) {
6038 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006039 keyEntry.eventTime = event.getEventTime();
6040 keyEntry.deviceId = event.getDeviceId();
6041 keyEntry.source = event.getSource();
6042 keyEntry.displayId = event.getDisplayId();
6043 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6044 keyEntry.keyCode = fallbackKeyCode;
6045 keyEntry.scanCode = event.getScanCode();
6046 keyEntry.metaState = event.getMetaState();
6047 keyEntry.repeatCount = event.getRepeatCount();
6048 keyEntry.downTime = event.getDownTime();
6049 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006050
6051#if DEBUG_OUTBOUND_EVENT_DETAILS
6052 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006053 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006054 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006055#endif
6056 return true; // restart the event
6057 } else {
6058#if DEBUG_OUTBOUND_EVENT_DETAILS
6059 ALOGD("Unhandled key event: No fallback key.");
6060#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006061
6062 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006063 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064 }
6065 }
6066 return false;
6067}
6068
6069bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006070 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006071 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072 return false;
6073}
6074
6075void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6076 mLock.unlock();
6077
Sean Stoutb4e0a592021-02-23 07:34:53 -08006078 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6079 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080
6081 mLock.lock();
6082}
6083
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084void InputDispatcher::traceInboundQueueLengthLocked() {
6085 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006086 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 }
6088}
6089
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006090void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 if (ATRACE_ENABLED()) {
6092 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006093 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6094 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 }
6096}
6097
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006098void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 if (ATRACE_ENABLED()) {
6100 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006101 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6102 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103 }
6104}
6105
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006106void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006107 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006109 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006110 dumpDispatchStateLocked(dump);
6111
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006112 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006113 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006114 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006115 }
6116}
6117
6118void InputDispatcher::monitor() {
6119 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006120 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006122 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123}
6124
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006125/**
6126 * Wake up the dispatcher and wait until it processes all events and commands.
6127 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6128 * this method can be safely called from any thread, as long as you've ensured that
6129 * the work you are interested in completing has already been queued.
6130 */
6131bool InputDispatcher::waitForIdle() {
6132 /**
6133 * Timeout should represent the longest possible time that a device might spend processing
6134 * events and commands.
6135 */
6136 constexpr std::chrono::duration TIMEOUT = 100ms;
6137 std::unique_lock lock(mLock);
6138 mLooper->wake();
6139 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6140 return result == std::cv_status::no_timeout;
6141}
6142
Vishnu Naire798b472020-07-23 13:52:21 -07006143/**
6144 * Sets focus to the window identified by the token. This must be called
6145 * after updating any input window handles.
6146 *
6147 * Params:
6148 * request.token - input channel token used to identify the window that should gain focus.
6149 * request.focusedToken - the token that the caller expects currently to be focused. If the
6150 * specified token does not match the currently focused window, this request will be dropped.
6151 * If the specified focused token matches the currently focused window, the call will succeed.
6152 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6153 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6154 * when requesting the focus change. This determines which request gets
6155 * precedence if there is a focus change request from another source such as pointer down.
6156 */
Vishnu Nair958da932020-08-21 17:12:37 -07006157void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6158 { // acquire lock
6159 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006160 std::optional<FocusResolver::FocusChanges> changes =
6161 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6162 if (changes) {
6163 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006164 }
6165 } // release lock
6166 // Wake up poll loop since it may need to make new input dispatching choices.
6167 mLooper->wake();
6168}
6169
Vishnu Nairc519ff72021-01-21 08:23:08 -08006170void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6171 if (changes.oldFocus) {
6172 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006173 if (focusedInputChannel) {
6174 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6175 "focus left window");
6176 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006177 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006178 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006179 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006180 if (changes.newFocus) {
6181 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006182 }
6183
Prabir Pradhan99987712020-11-10 18:43:05 -08006184 // If a window has pointer capture, then it must have focus. We need to ensure that this
6185 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6186 // If the window loses focus before it loses pointer capture, then the window can be in a state
6187 // where it has pointer capture but not focus, violating the contract. Therefore we must
6188 // dispatch the pointer capture event before the focus event. Since focus events are added to
6189 // the front of the queue (above), we add the pointer capture event to the front of the queue
6190 // after the focus events are added. This ensures the pointer capture event ends up at the
6191 // front.
6192 disablePointerCaptureForcedLocked();
6193
Vishnu Nairc519ff72021-01-21 08:23:08 -08006194 if (mFocusedDisplayId == changes.displayId) {
6195 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006196 }
6197}
Vishnu Nair958da932020-08-21 17:12:37 -07006198
Prabir Pradhan99987712020-11-10 18:43:05 -08006199void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhanf192a102021-08-06 14:01:18 +00006200 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006201 return;
6202 }
6203
6204 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6205
Prabir Pradhanf192a102021-08-06 14:01:18 +00006206 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006207 setPointerCaptureLocked(false);
6208 }
6209
6210 if (!mWindowTokenWithPointerCapture) {
6211 // No need to send capture changes because no window has capture.
6212 return;
6213 }
6214
6215 if (mPendingEvent != nullptr) {
6216 // Move the pending event to the front of the queue. This will give the chance
6217 // for the pending event to be dropped if it is a captured event.
6218 mInboundQueue.push_front(mPendingEvent);
6219 mPendingEvent = nullptr;
6220 }
6221
6222 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhanf192a102021-08-06 14:01:18 +00006223 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006224 mInboundQueue.push_front(std::move(entry));
6225}
6226
Prabir Pradhan99987712020-11-10 18:43:05 -08006227void InputDispatcher::setPointerCaptureLocked(bool enabled) {
Prabir Pradhanf192a102021-08-06 14:01:18 +00006228 mCurrentPointerCaptureRequest.enable = enabled;
6229 mCurrentPointerCaptureRequest.seq++;
Prabir Pradhan99987712020-11-10 18:43:05 -08006230 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6231 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
Prabir Pradhanf192a102021-08-06 14:01:18 +00006232 commandEntry->pointerCaptureRequest = mCurrentPointerCaptureRequest;
Prabir Pradhan99987712020-11-10 18:43:05 -08006233 postCommandLocked(std::move(commandEntry));
6234}
6235
6236void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6237 android::inputdispatcher::CommandEntry* commandEntry) {
6238 mLock.unlock();
6239
Prabir Pradhanf192a102021-08-06 14:01:18 +00006240 mPolicy->setPointerCapture(commandEntry->pointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006241
6242 mLock.lock();
6243}
6244
Vishnu Nair599f1412021-06-21 10:39:58 -07006245void InputDispatcher::displayRemoved(int32_t displayId) {
6246 { // acquire lock
6247 std::scoped_lock _l(mLock);
6248 // Set an empty list to remove all handles from the specific display.
6249 setInputWindowsLocked(/* window handles */ {}, displayId);
6250 setFocusedApplicationLocked(displayId, nullptr);
6251 // Call focus resolver to clean up stale requests. This must be called after input windows
6252 // have been removed for the removed display.
6253 mFocusResolver.displayRemoved(displayId);
6254 } // release lock
6255
6256 // Wake up poll loop since it may need to make new input dispatching choices.
6257 mLooper->wake();
6258}
6259
Garfield Tane84e6f92019-08-29 17:28:41 -07006260} // namespace android::inputdispatcher