blob: c2a2794eb9487718a6a4d79840e1b317a06d8c10 [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 mFocusedWindowRequestedPointerCapture(false),
527 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000528 mLatencyAggregator(),
529 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000530 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800532 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
Yi Kong9b14ac62018-07-17 13:48:38 -0700534 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535
536 policy->getDispatcherConfiguration(&mConfig);
537}
538
539InputDispatcher::~InputDispatcher() {
540 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800541 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542
543 resetKeyRepeatLocked();
544 releasePendingEventLocked();
545 drainInboundQueueLocked();
546 }
547
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000548 while (!mConnectionsByToken.empty()) {
549 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700550 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 }
552}
553
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700554status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700555 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700556 return ALREADY_EXISTS;
557 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700558 mThread = std::make_unique<InputThread>(
559 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
560 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700561}
562
563status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700564 if (mThread && mThread->isCallingThread()) {
565 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700566 return INVALID_OPERATION;
567 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700568 mThread.reset();
569 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700570}
571
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572void InputDispatcher::dispatchOnce() {
573 nsecs_t nextWakeupTime = LONG_LONG_MAX;
574 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800575 std::scoped_lock _l(mLock);
576 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
578 // Run a dispatch loop if there are no pending commands.
579 // The dispatch loop might enqueue commands to run afterwards.
580 if (!haveCommandsLocked()) {
581 dispatchOnceInnerLocked(&nextWakeupTime);
582 }
583
584 // Run all pending commands if there are any.
585 // If any commands were run then force the next poll to wake up immediately.
586 if (runCommandsLockedInterruptible()) {
587 nextWakeupTime = LONG_LONG_MIN;
588 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800589
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700590 // If we are still waiting for ack on some events,
591 // we might have to wake up earlier to check if an app is anr'ing.
592 const nsecs_t nextAnrCheck = processAnrsLocked();
593 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
594
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800595 // We are about to enter an infinitely long sleep, because we have no commands or
596 // pending or queued events
597 if (nextWakeupTime == LONG_LONG_MAX) {
598 mDispatcherEnteredIdle.notify_all();
599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 } // release lock
601
602 // Wait for callback or timeout or wake. (make sure we round up, not down)
603 nsecs_t currentTime = now();
604 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
605 mLooper->pollOnce(timeoutMillis);
606}
607
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700608/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500609 * Raise ANR if there is no focused window.
610 * Before the ANR is raised, do a final state check:
611 * 1. The currently focused application must be the same one we are waiting for.
612 * 2. Ensure we still don't have a focused window.
613 */
614void InputDispatcher::processNoFocusedWindowAnrLocked() {
615 // Check if the application that we are waiting for is still focused.
616 std::shared_ptr<InputApplicationHandle> focusedApplication =
617 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
618 if (focusedApplication == nullptr ||
619 focusedApplication->getApplicationToken() !=
620 mAwaitedFocusedApplication->getApplicationToken()) {
621 // Unexpected because we should have reset the ANR timer when focused application changed
622 ALOGE("Waited for a focused window, but focused application has already changed to %s",
623 focusedApplication->getName().c_str());
624 return; // The focused application has changed.
625 }
626
627 const sp<InputWindowHandle>& focusedWindowHandle =
628 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
629 if (focusedWindowHandle != nullptr) {
630 return; // We now have a focused window. No need for ANR.
631 }
632 onAnrLocked(mAwaitedFocusedApplication);
633}
634
635/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700636 * Check if any of the connections' wait queues have events that are too old.
637 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
638 * Return the time at which we should wake up next.
639 */
640nsecs_t InputDispatcher::processAnrsLocked() {
641 const nsecs_t currentTime = now();
642 nsecs_t nextAnrCheck = LONG_LONG_MAX;
643 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
644 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
645 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500646 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700647 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500648 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700649 return LONG_LONG_MIN;
650 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500651 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700652 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
653 }
654 }
655
656 // Check if any connection ANRs are due
657 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
658 if (currentTime < nextAnrCheck) { // most likely scenario
659 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
660 }
661
662 // If we reached here, we have an unresponsive connection.
663 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
664 if (connection == nullptr) {
665 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
666 return nextAnrCheck;
667 }
668 connection->responsive = false;
669 // Stop waking up for this unresponsive connection
670 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000671 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700672 return LONG_LONG_MIN;
673}
674
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500675std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700676 sp<InputWindowHandle> window = getWindowHandleLocked(token);
677 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500678 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700679 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500680 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700681}
682
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
684 nsecs_t currentTime = now();
685
Jeff Browndc5992e2014-04-11 01:27:26 -0700686 // Reset the key repeat timer whenever normal dispatch is suspended while the
687 // device is in a non-interactive state. This is to ensure that we abort a key
688 // repeat if the device is just coming out of sleep.
689 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 resetKeyRepeatLocked();
691 }
692
693 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
694 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100695 if (DEBUG_FOCUS) {
696 ALOGD("Dispatch frozen. Waiting some more.");
697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 return;
699 }
700
701 // Optimize latency of app switches.
702 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
703 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
704 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
705 if (mAppSwitchDueTime < *nextWakeupTime) {
706 *nextWakeupTime = mAppSwitchDueTime;
707 }
708
709 // Ready to start a new event.
710 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700712 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 if (isAppSwitchDue) {
714 // The inbound queue is empty so the app switch key we were waiting
715 // for will never arrive. Stop waiting for it.
716 resetPendingAppSwitchLocked(false);
717 isAppSwitchDue = false;
718 }
719
720 // Synthesize a key repeat if appropriate.
721 if (mKeyRepeatState.lastKeyEntry) {
722 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
723 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
724 } else {
725 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
726 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
727 }
728 }
729 }
730
731 // Nothing to do if there is no pending event.
732 if (!mPendingEvent) {
733 return;
734 }
735 } else {
736 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700737 mPendingEvent = mInboundQueue.front();
738 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 traceInboundQueueLengthLocked();
740 }
741
742 // Poke user activity for this event.
743 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700744 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 }
747
748 // Now we have an event to dispatch.
749 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700750 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700752 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700754 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700756 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 }
758
759 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700760 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 }
762
763 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700764 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700765 const ConfigurationChangedEntry& typedEntry =
766 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700767 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700768 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 break;
770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700773 const DeviceResetEntry& typedEntry =
774 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700776 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100780 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700781 std::shared_ptr<FocusEntry> typedEntry =
782 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100783 dispatchFocusLocked(currentTime, typedEntry);
784 done = true;
785 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
786 break;
787 }
788
Prabir Pradhan99987712020-11-10 18:43:05 -0800789 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
790 const auto typedEntry =
791 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
792 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
793 done = true;
794 break;
795 }
796
arthurhungb89ccb02020-12-30 16:19:01 +0800797 case EventEntry::Type::DRAG: {
798 std::shared_ptr<DragEntry> typedEntry =
799 std::static_pointer_cast<DragEntry>(mPendingEvent);
800 dispatchDragLocked(currentTime, typedEntry);
801 done = true;
802 break;
803 }
804
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700805 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700806 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 resetPendingAppSwitchLocked(true);
810 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 } else if (dropReason == DropReason::NOT_DROPPED) {
812 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 }
814 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700815 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700818 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
819 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700821 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 break;
823 }
824
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700825 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700826 std::shared_ptr<MotionEntry> motionEntry =
827 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700828 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
829 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700831 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700832 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
835 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700836 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700837 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
Chris Yef59a2f42020-10-16 12:55:26 -0700840
841 case EventEntry::Type::SENSOR: {
842 std::shared_ptr<SensorEntry> sensorEntry =
843 std::static_pointer_cast<SensorEntry>(mPendingEvent);
844 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
845 dropReason = DropReason::APP_SWITCH;
846 }
847 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
848 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
849 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
850 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
851 dropReason = DropReason::STALE;
852 }
853 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
854 done = true;
855 break;
856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 }
858
859 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700860 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700861 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
Michael Wright3a981722015-06-10 15:26:13 +0100863 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864
865 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
868}
869
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700870/**
871 * Return true if the events preceding this incoming motion event should be dropped
872 * Return false otherwise (the default behaviour)
873 */
874bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700875 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700876 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877
878 // Optimize case where the current application is unresponsive and the user
879 // decides to touch a window in a different application.
880 // If the application takes too long to catch up then we drop all events preceding
881 // the touch into the other window.
882 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700883 int32_t displayId = motionEntry.displayId;
884 int32_t x = static_cast<int32_t>(
885 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
886 int32_t y = static_cast<int32_t>(
887 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
888 sp<InputWindowHandle> touchedWindowHandle =
889 findTouchedWindowAtLocked(displayId, x, y, nullptr);
890 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891 touchedWindowHandle->getApplicationToken() !=
892 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700893 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700894 ALOGI("Pruning input queue because user touched a different application while waiting "
895 "for %s",
896 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700897 return true;
898 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899
900 // Alternatively, maybe there's a gesture monitor that could handle this event
901 std::vector<TouchedMonitor> gestureMonitors =
902 findTouchedGestureMonitorsLocked(displayId, {});
903 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
904 sp<Connection> connection =
905 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000906 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907 // This monitor could take more input. Drop all events preceding this
908 // event, so that gesture monitor could get a chance to receive the stream
909 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
910 "responsive gesture monitor that may handle the event",
911 mAwaitedFocusedApplication->getName().c_str());
912 return true;
913 }
914 }
915 }
916
917 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
918 // yet been processed by some connections, the dispatcher will wait for these motion
919 // events to be processed before dispatching the key event. This is because these motion events
920 // may cause a new window to be launched, which the user might expect to receive focus.
921 // To prevent waiting forever for such events, just send the key to the currently focused window
922 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
923 ALOGD("Received a new pointer down event, stop waiting for events to process and "
924 "just send the pending key event to the focused window.");
925 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 }
927 return false;
928}
929
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700930bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700931 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700932 mInboundQueue.push_back(std::move(newEntry));
933 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 traceInboundQueueLengthLocked();
935
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700936 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700937 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 // Optimize app switch latency.
939 // If the application takes too long to catch up then we drop all events preceding
940 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700941 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700942 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700943 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700945 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700948 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700950 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 mAppSwitchSawKeyDown = false;
952 needWake = true;
953 }
954 }
955 }
956 break;
957 }
958
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700959 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700960 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
961 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700962 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100966 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700967 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
968 break;
969 }
970 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800971 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700972 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800973 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
974 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700975 // nothing to do
976 break;
977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
979
980 return needWake;
981}
982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700984 // Do not store sensor event in recent queue to avoid flooding the queue.
985 if (entry->type != EventEntry::Type::SENSOR) {
986 mRecentQueue.push_back(entry);
987 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700988 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700989 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
991}
992
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700994 int32_t y, TouchState* touchState,
995 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800996 bool addPortalWindows,
997 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700998 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
999 LOG_ALWAYS_FATAL(
1000 "Must provide a valid touch state if adding portal windows or outside targets");
1001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -07001003 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001004 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001005 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001006 continue;
1007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1009 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001010 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011
1012 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001013 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1014 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1015 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001017 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1019 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001020 if (addPortalWindows) {
1021 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001022 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001023 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001024 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 // Found window.
1028 return windowHandle;
1029 }
1030 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001031
Michael Wright44753b12020-07-08 13:48:11 +01001032 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001033 touchState->addOrUpdateWindow(windowHandle,
1034 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1035 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041}
1042
Garfield Tane84e6f92019-08-29 17:28:41 -07001043std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001044 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001045 std::vector<TouchedMonitor> touchedMonitors;
1046
1047 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1048 addGestureMonitors(monitors, touchedMonitors);
1049 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1050 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1051 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1053 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001054 }
1055 return touchedMonitors;
1056}
1057
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001058void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 const char* reason;
1060 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001061 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001063 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 reason = "inbound event was dropped because the policy consumed it";
1066 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001067 case DropReason::DISABLED:
1068 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 ALOGI("Dropped event because input dispatch is disabled.");
1070 }
1071 reason = "inbound event was dropped because input dispatch is disabled";
1072 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001073 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 ALOGI("Dropped event because of pending overdue app switch.");
1075 reason = "inbound event was dropped because of pending overdue app switch";
1076 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 ALOGI("Dropped event because the current application is not responding and the user "
1079 "has started interacting with a different application.");
1080 reason = "inbound event was dropped because the current application is not responding "
1081 "and the user has started interacting with a different application";
1082 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 ALOGI("Dropped event because it is stale.");
1085 reason = "inbound event was dropped because it is stale";
1086 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001087 case DropReason::NO_POINTER_CAPTURE:
1088 ALOGI("Dropped event because there is no window with Pointer Capture.");
1089 reason = "inbound event was dropped because there is no window with Pointer Capture";
1090 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 case DropReason::NOT_DROPPED: {
1092 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001097 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001098 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1100 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001103 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1105 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1107 synthesizeCancelationEventsForAllConnectionsLocked(options);
1108 } else {
1109 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1110 synthesizeCancelationEventsForAllConnectionsLocked(options);
1111 }
1112 break;
1113 }
Chris Yef59a2f42020-10-16 12:55:26 -07001114 case EventEntry::Type::SENSOR: {
1115 break;
1116 }
arthurhungb89ccb02020-12-30 16:19:01 +08001117 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1118 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001119 break;
1120 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001121 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001122 case EventEntry::Type::CONFIGURATION_CHANGED:
1123 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001124 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001125 break;
1126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128}
1129
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001130static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1132 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133}
1134
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001135bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1136 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1137 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1138 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139}
1140
1141bool InputDispatcher::isAppSwitchPendingLocked() {
1142 return mAppSwitchDueTime != LONG_LONG_MAX;
1143}
1144
1145void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1146 mAppSwitchDueTime = LONG_LONG_MAX;
1147
1148#if DEBUG_APP_SWITCH
1149 if (handled) {
1150 ALOGD("App switch has arrived.");
1151 } else {
1152 ALOGD("App switch was abandoned.");
1153 }
1154#endif
1155}
1156
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001158 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159}
1160
1161bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001162 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 return false;
1164 }
1165
1166 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001167 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001168 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001170 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171
1172 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001173 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 return true;
1175}
1176
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001177void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1178 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179}
1180
1181void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001182 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001183 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001184 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 releaseInboundEventLocked(entry);
1186 }
1187 traceInboundQueueLengthLocked();
1188}
1189
1190void InputDispatcher::releasePendingEventLocked() {
1191 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001193 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195}
1196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001199 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200#if DEBUG_DISPATCH_CYCLE
1201 ALOGD("Injected inbound event was dropped.");
1202#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 }
1205 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001206 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
1208 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209}
1210
1211void InputDispatcher::resetKeyRepeatLocked() {
1212 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001213 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 }
1215}
1216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1218 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
Michael Wright2e732952014-09-24 13:26:59 -07001220 uint32_t policyFlags = entry->policyFlags &
1221 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223 std::shared_ptr<KeyEntry> newEntry =
1224 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1225 entry->source, entry->displayId, policyFlags, entry->action,
1226 entry->flags, entry->keyCode, entry->scanCode,
1227 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001229 newEntry->syntheticRepeat = true;
1230 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001232 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239#endif
1240
1241 // Reset key repeating in case a keyboard device was added or removed or something.
1242 resetKeyRepeatLocked();
1243
1244 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001245 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1246 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001248 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 return true;
1250}
1251
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1253 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1256 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257#endif
1258
liushenxiang42232912021-05-21 20:24:09 +08001259 // Reset key repeating in case a keyboard device was disabled or enabled.
1260 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1261 resetKeyRepeatLocked();
1262 }
1263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 synthesizeCancelationEventsForAllConnectionsLocked(options);
1267 return true;
1268}
1269
Vishnu Nairad321cd2020-08-20 16:40:21 -07001270void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001271 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001272 if (mPendingEvent != nullptr) {
1273 // Move the pending event to the front of the queue. This will give the chance
1274 // for the pending event to get dispatched to the newly focused window
1275 mInboundQueue.push_front(mPendingEvent);
1276 mPendingEvent = nullptr;
1277 }
1278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279 std::unique_ptr<FocusEntry> focusEntry =
1280 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1281 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001282
1283 // This event should go to the front of the queue, but behind all other focus events
1284 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001285 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001286 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 [](const std::shared_ptr<EventEntry>& event) {
1288 return event->type == EventEntry::Type::FOCUS;
1289 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001290
1291 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001293}
1294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001296 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001297 if (channel == nullptr) {
1298 return; // Window has gone away
1299 }
1300 InputTarget target;
1301 target.inputChannel = channel;
1302 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1303 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001304 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1305 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001306 std::string reason = std::string("reason=").append(entry->reason);
1307 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001308 dispatchEventLocked(currentTime, entry, {target});
1309}
1310
Prabir Pradhan99987712020-11-10 18:43:05 -08001311void InputDispatcher::dispatchPointerCaptureChangedLocked(
1312 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1313 DropReason& dropReason) {
1314 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001315 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1316 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1317 }
1318 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001319 // Pointer capture was already forcefully disabled because of focus change.
1320 dropReason = DropReason::NOT_DROPPED;
1321 return;
1322 }
1323
1324 // Set drop reason for early returns
1325 dropReason = DropReason::NO_POINTER_CAPTURE;
1326
1327 sp<IBinder> token;
1328 if (entry->pointerCaptureEnabled) {
1329 // Enable Pointer Capture
1330 if (!mFocusedWindowRequestedPointerCapture) {
1331 // This can happen if a window requests capture and immediately releases capture.
1332 ALOGW("No window requested Pointer Capture.");
1333 return;
1334 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001335 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001336 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1337 mWindowTokenWithPointerCapture = token;
1338 } else {
1339 // Disable Pointer Capture
1340 token = mWindowTokenWithPointerCapture;
1341 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001342 if (mFocusedWindowRequestedPointerCapture) {
1343 mFocusedWindowRequestedPointerCapture = false;
1344 setPointerCaptureLocked(false);
1345 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001346 }
1347
1348 auto channel = getInputChannelLocked(token);
1349 if (channel == nullptr) {
1350 // Window has gone away, clean up Pointer Capture state.
1351 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001352 if (mFocusedWindowRequestedPointerCapture) {
1353 mFocusedWindowRequestedPointerCapture = false;
1354 setPointerCaptureLocked(false);
1355 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001356 return;
1357 }
1358 InputTarget target;
1359 target.inputChannel = channel;
1360 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1361 entry->dispatchInProgress = true;
1362 dispatchEventLocked(currentTime, entry, {target});
1363
1364 dropReason = DropReason::NOT_DROPPED;
1365}
1366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 if (!entry->dispatchInProgress) {
1371 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1372 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1373 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1374 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001375 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 // We have seen two identical key downs in a row which indicates that the device
1377 // driver is automatically generating key repeats itself. We take note of the
1378 // repeat here, but we disable our own next key repeat timer since it is clear that
1379 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001380 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1381 // Make sure we don't get key down from a different device. If a different
1382 // device Id has same key pressed down, the new device Id will replace the
1383 // current one to hold the key repeat with repeat count reset.
1384 // In the future when got a KEY_UP on the device id, drop it and do not
1385 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1387 resetKeyRepeatLocked();
1388 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1389 } else {
1390 // Not a repeat. Save key down state in case we do see a repeat later.
1391 resetKeyRepeatLocked();
1392 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1393 }
1394 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001395 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1396 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001397 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001398#if DEBUG_INBOUND_EVENT_DETAILS
1399 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1400#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001401 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 resetKeyRepeatLocked();
1403 }
1404
1405 if (entry->repeatCount == 1) {
1406 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1407 } else {
1408 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1409 }
1410
1411 entry->dispatchInProgress = true;
1412
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001413 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415
1416 // Handle case where the policy asked us to try again later last time.
1417 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1418 if (currentTime < entry->interceptKeyWakeupTime) {
1419 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1420 *nextWakeupTime = entry->interceptKeyWakeupTime;
1421 }
1422 return false; // wait until next wakeup
1423 }
1424 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1425 entry->interceptKeyWakeupTime = 0;
1426 }
1427
1428 // Give the policy a chance to intercept the key.
1429 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1430 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001431 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001432 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001433 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001434 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001435 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001437 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 return false; // wait for the command to run
1439 } else {
1440 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1441 }
1442 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001443 if (*dropReason == DropReason::NOT_DROPPED) {
1444 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 }
1446 }
1447
1448 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001449 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001450 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001451 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1452 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001453 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 return true;
1455 }
1456
1457 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001458 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001459 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001460 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 return false;
1463 }
1464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 return true;
1468 }
1469
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001470 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001471 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472
1473 // Dispatch the key.
1474 dispatchEventLocked(currentTime, entry, inputTargets);
1475 return true;
1476}
1477
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001480 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001481 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1482 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001483 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1484 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1485 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486#endif
1487}
1488
Chris Yef59a2f42020-10-16 12:55:26 -07001489void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1490 mLock.unlock();
1491
1492 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1493 if (entry->accuracyChanged) {
1494 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1495 }
1496 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1497 entry->hwTimestamp, entry->values);
1498 mLock.lock();
1499}
1500
1501void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1502 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1503#if DEBUG_OUTBOUND_EVENT_DETAILS
1504 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1505 "source=0x%x, sensorType=%s",
1506 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001507 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001508#endif
1509 std::unique_ptr<CommandEntry> commandEntry =
1510 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1511 commandEntry->sensorEntry = entry;
1512 postCommandLocked(std::move(commandEntry));
1513}
1514
1515bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1516#if DEBUG_OUTBOUND_EVENT_DETAILS
1517 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1518 NamedEnum::string(sensorType).c_str());
1519#endif
1520 { // acquire lock
1521 std::scoped_lock _l(mLock);
1522
1523 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1524 std::shared_ptr<EventEntry> entry = *it;
1525 if (entry->type == EventEntry::Type::SENSOR) {
1526 it = mInboundQueue.erase(it);
1527 releaseInboundEventLocked(entry);
1528 }
1529 }
1530 }
1531 return true;
1532}
1533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001534bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001535 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001536 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001538 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 entry->dispatchInProgress = true;
1540
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001541 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 }
1543
1544 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001545 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001546 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1548 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 return true;
1550 }
1551
1552 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1553
1554 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001555 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556
1557 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001558 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 if (isPointerEvent) {
1560 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001562 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 } else {
1565 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001566 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return false;
1571 }
1572
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001575 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1576 return true;
1577 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001579 CancelationOptions::Mode mode(isPointerEvent
1580 ? CancelationOptions::CANCEL_POINTER_EVENTS
1581 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1582 CancelationOptions options(mode, "input event injection failed");
1583 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 return true;
1585 }
1586
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001587 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001588 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001590 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001591 std::unordered_map<int32_t, TouchState>::iterator it =
1592 mTouchStatesByDisplay.find(entry->displayId);
1593 if (it != mTouchStatesByDisplay.end()) {
1594 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001595 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001596 // The event has gone through these portal windows, so we add monitoring targets of
1597 // the corresponding displays as well.
1598 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001599 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001600 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001601 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001602 }
1603 }
1604 }
1605 }
1606
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 // Dispatch the motion.
1608 if (conflictingPointerActions) {
1609 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 synthesizeCancelationEventsForAllConnectionsLocked(options);
1612 }
1613 dispatchEventLocked(currentTime, entry, inputTargets);
1614 return true;
1615}
1616
arthurhungb89ccb02020-12-30 16:19:01 +08001617void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1618 bool isExiting, const MotionEntry& motionEntry) {
1619 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1620 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1621 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1622 PointerCoords pointerCoords;
1623 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1624 pointerCoords.transform(windowHandle->getInfo()->transform);
1625
1626 std::unique_ptr<DragEntry> dragEntry =
1627 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1628 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1629 pointerCoords.getY());
1630
1631 enqueueInboundEventLocked(std::move(dragEntry));
1632}
1633
1634void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1635 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1636 if (channel == nullptr) {
1637 return; // Window has gone away
1638 }
1639 InputTarget target;
1640 target.inputChannel = channel;
1641 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1642 entry->dispatchInProgress = true;
1643 dispatchEventLocked(currentTime, entry, {target});
1644}
1645
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001646void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001648 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 ", policyFlags=0x%x, "
1650 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1651 "metaState=0x%x, buttonState=0x%x,"
1652 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1654 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1655 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001659 "x=%f, y=%f, pressure=%f, size=%f, "
1660 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1661 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001662 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1663 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1664 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1665 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1666 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1667 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1668 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1669 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1670 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1671 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 }
1673#endif
1674}
1675
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001676void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1677 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001678 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001679 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680#if DEBUG_DISPATCH_CYCLE
1681 ALOGD("dispatchEventToCurrentInputTargets");
1682#endif
1683
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001684 updateInteractionTokensLocked(*eventEntry, inputTargets);
1685
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1687
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001688 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001690 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001691 sp<Connection> connection =
1692 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001693 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001694 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001696 if (DEBUG_FOCUS) {
1697 ALOGD("Dropping event delivery to target with channel '%s' because it "
1698 "is no longer registered with the input dispatcher.",
1699 inputTarget.inputChannel->getName().c_str());
1700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702 }
1703}
1704
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001705void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1706 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1707 // If the policy decides to close the app, we will get a channel removal event via
1708 // unregisterInputChannel, and will clean up the connection that way. We are already not
1709 // sending new pointers to the connection when it blocked, but focused events will continue to
1710 // pile up.
1711 ALOGW("Canceling events for %s because it is unresponsive",
1712 connection->inputChannel->getName().c_str());
1713 if (connection->status == Connection::STATUS_NORMAL) {
1714 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1715 "application not responding");
1716 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718}
1719
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001720void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001721 if (DEBUG_FOCUS) {
1722 ALOGD("Resetting ANR timeouts.");
1723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724
1725 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001726 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001727 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728}
1729
Tiger Huang721e26f2018-07-24 22:26:19 +08001730/**
1731 * Get the display id that the given event should go to. If this event specifies a valid display id,
1732 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1733 * Focused display is the display that the user most recently interacted with.
1734 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001736 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001738 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001739 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1740 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 break;
1742 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001743 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001744 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1745 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001746 break;
1747 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001748 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001749 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001750 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001751 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001752 case EventEntry::Type::SENSOR:
1753 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001754 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001755 return ADISPLAY_ID_NONE;
1756 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001757 }
1758 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1759}
1760
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001761bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1762 const char* focusedWindowName) {
1763 if (mAnrTracker.empty()) {
1764 // already processed all events that we waited for
1765 mKeyIsWaitingForEventsTimeout = std::nullopt;
1766 return false;
1767 }
1768
1769 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1770 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001771 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001772 mKeyIsWaitingForEventsTimeout = currentTime +
1773 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1774 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001775 return true;
1776 }
1777
1778 // We still have pending events, and already started the timer
1779 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1780 return true; // Still waiting
1781 }
1782
1783 // Waited too long, and some connection still hasn't processed all motions
1784 // Just send the key to the focused window
1785 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1786 focusedWindowName);
1787 mKeyIsWaitingForEventsTimeout = std::nullopt;
1788 return false;
1789}
1790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001791InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1792 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1793 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001794 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795
Tiger Huang721e26f2018-07-24 22:26:19 +08001796 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001797 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001798 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001799 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1800
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 // If there is no currently focused window and no focused application
1802 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001803 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1804 ALOGI("Dropping %s event because there is no focused window or focused application in "
1805 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001806 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001807 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 }
1809
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001810 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1811 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1812 // start interacting with another application via touch (app switch). This code can be removed
1813 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1814 // an app is expected to have a focused window.
1815 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1816 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1817 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001818 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1819 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1820 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001821 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001822 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 ALOGW("Waiting because no window has focus but %s may eventually add a "
1824 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001825 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001826 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001827 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001828 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1829 // Already raised ANR. Drop the event
1830 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001831 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833 } else {
1834 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 }
1837 }
1838
1839 // we have a valid, non-null focused window
1840 resetNoFocusedWindowTimeoutLocked();
1841
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001843 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 }
1846
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001847 if (focusedWindowHandle->getInfo()->paused) {
1848 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001849 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001850 }
1851
1852 // If the event is a key event, then we must wait for all previous events to
1853 // complete before delivering it because previous events may have the
1854 // side-effect of transferring focus to a different window and we want to
1855 // ensure that the following keys are sent to the new window.
1856 //
1857 // Suppose the user touches a button in a window then immediately presses "A".
1858 // If the button causes a pop-up window to appear then we want to ensure that
1859 // the "A" key is delivered to the new pop-up window. This is because users
1860 // often anticipate pending UI changes when typing on a keyboard.
1861 // To obtain this behavior, we must serialize key events with respect to all
1862 // prior input events.
1863 if (entry.type == EventEntry::Type::KEY) {
1864 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1865 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001866 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
1869
1870 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001871 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1873 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874
1875 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877}
1878
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879/**
1880 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1881 * that are currently unresponsive.
1882 */
1883std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1884 const std::vector<TouchedMonitor>& monitors) const {
1885 std::vector<TouchedMonitor> responsiveMonitors;
1886 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1887 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1888 sp<Connection> connection = getConnectionLocked(
1889 monitor.monitor.inputChannel->getConnectionToken());
1890 if (connection == nullptr) {
1891 ALOGE("Could not find connection for monitor %s",
1892 monitor.monitor.inputChannel->getName().c_str());
1893 return false;
1894 }
1895 if (!connection->responsive) {
1896 ALOGW("Unresponsive monitor %s will not get the new gesture",
1897 connection->inputChannel->getName().c_str());
1898 return false;
1899 }
1900 return true;
1901 });
1902 return responsiveMonitors;
1903}
1904
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001905InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1906 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1907 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001908 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 enum InjectionPermission {
1910 INJECTION_PERMISSION_UNKNOWN,
1911 INJECTION_PERMISSION_GRANTED,
1912 INJECTION_PERMISSION_DENIED
1913 };
1914
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 // For security reasons, we defer updating the touch state until we are sure that
1916 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001917 int32_t displayId = entry.displayId;
1918 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1920
1921 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001922 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001924 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1925 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001927 // Copy current touch state into tempTouchState.
1928 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1929 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001930 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001931 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001932 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1933 mTouchStatesByDisplay.find(displayId);
1934 if (oldStateIt != mTouchStatesByDisplay.end()) {
1935 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001936 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001937 }
1938
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 bool isSplit = tempTouchState.split;
1940 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1941 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1942 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1944 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1945 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1946 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1947 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001948 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 bool wrongDevice = false;
1950 if (newGesture) {
1951 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001953 ALOGI("Dropping event because a pointer for a different device is already down "
1954 "in display %" PRId32,
1955 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001956 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001957 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958 switchedDevice = false;
1959 wrongDevice = true;
1960 goto Failed;
1961 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001962 tempTouchState.reset();
1963 tempTouchState.down = down;
1964 tempTouchState.deviceId = entry.deviceId;
1965 tempTouchState.source = entry.source;
1966 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001968 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001969 ALOGI("Dropping move event because a pointer for a different device is already active "
1970 "in display %" PRId32,
1971 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001972 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001973 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001974 switchedDevice = false;
1975 wrongDevice = true;
1976 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
1978
1979 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1980 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1981
Garfield Tan00f511d2019-06-12 16:55:40 -07001982 int32_t x;
1983 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001985 // Always dispatch mouse events to cursor position.
1986 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987 x = int32_t(entry.xCursorPosition);
1988 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001989 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001990 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1991 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001992 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001993 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001994 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001995 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1996 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001997
1998 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002003 if (newTouchedWindowHandle != nullptr &&
2004 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002005 // New window supports splitting, but we should never split mouse events.
2006 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 } else if (isSplit) {
2008 // New window does not support splitting but we have already split events.
2009 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002010 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 }
2012
2013 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002014 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002016 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002017 }
2018
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002019 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2020 ALOGI("Not sending touch event to %s because it is paused",
2021 newTouchedWindowHandle->getName().c_str());
2022 newTouchedWindowHandle = nullptr;
2023 }
2024
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002025 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002027 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2028 if (!isResponsive) {
2029 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002030 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2031 newTouchedWindowHandle = nullptr;
2032 }
2033 }
2034
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002035 // Drop events that can't be trusted due to occlusion
2036 if (newTouchedWindowHandle != nullptr &&
2037 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2038 TouchOcclusionInfo occlusionInfo =
2039 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002040 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002041 if (DEBUG_TOUCH_OCCLUSION) {
2042 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2043 for (const auto& log : occlusionInfo.debugInfo) {
2044 ALOGD("%s", log.c_str());
2045 }
2046 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002047 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2048 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2049 ALOGW("Dropping untrusted touch event due to %s/%d",
2050 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2051 newTouchedWindowHandle = nullptr;
2052 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002053 }
2054 }
2055
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002056 // Also don't send the new touch event to unresponsive gesture monitors
2057 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2058
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2060 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002061 "(%d, %d) in display %" PRId32 ".",
2062 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002063 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002064 goto Failed;
2065 }
2066
2067 if (newTouchedWindowHandle != nullptr) {
2068 // Set target flags.
2069 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2070 if (isSplit) {
2071 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002073 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2074 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2075 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2076 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2077 }
2078
2079 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002080 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2081 newHoverWindowHandle = nullptr;
2082 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002083 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002084 }
2085
2086 // Update the temporary touch state.
2087 BitSet32 pointerIds;
2088 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002089 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002090 pointerIds.markBit(pointerId);
2091 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002092 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 }
2094
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 } else {
2097 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2098
2099 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002101 if (DEBUG_FOCUS) {
2102 ALOGD("Dropping event because the pointer is not down or we previously "
2103 "dropped the pointer down event in display %" PRId32,
2104 displayId);
2105 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002106 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 goto Failed;
2108 }
2109
arthurhung6d4bed92021-03-17 11:59:33 +08002110 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002111
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002113 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002114 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002115 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2116 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117
2118 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002119 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002120 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2122 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002123 if (DEBUG_FOCUS) {
2124 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2125 oldTouchedWindowHandle->getName().c_str(),
2126 newTouchedWindowHandle->getName().c_str(), displayId);
2127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002129 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2130 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2131 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132
2133 // Make a slippery entrance into the new window.
2134 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2135 isSplit = true;
2136 }
2137
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002138 int32_t targetFlags =
2139 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 if (isSplit) {
2141 targetFlags |= InputTarget::FLAG_SPLIT;
2142 }
2143 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2144 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002145 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2146 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 }
2148
2149 BitSet32 pointerIds;
2150 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002151 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155 }
2156 }
2157
2158 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002159 // Let the previous window know that the hover sequence is over, unless we already did it
2160 // when dispatching it as is to newTouchedWindowHandle.
2161 if (mLastHoverWindowHandle != nullptr &&
2162 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2163 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164#if DEBUG_HOVER
2165 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002166 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002168 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2169 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171
Garfield Tandf26e862020-07-01 20:18:19 -07002172 // Let the new window know that the hover sequence is starting, unless we already did it
2173 // when dispatching it as is to newTouchedWindowHandle.
2174 if (newHoverWindowHandle != nullptr &&
2175 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2176 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177#if DEBUG_HOVER
2178 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002181 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2182 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2183 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
2185 }
2186
2187 // Check permission to inject into all touched foreground windows and ensure there
2188 // is at least one touched foreground window.
2189 {
2190 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002191 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2193 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002194 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002195 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 injectionPermission = INJECTION_PERMISSION_DENIED;
2197 goto Failed;
2198 }
2199 }
2200 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002201 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002202 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002203 ALOGI("Dropping event because there is no touched foreground window in display "
2204 "%" PRId32 " or gesture monitor to receive it.",
2205 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002206 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 goto Failed;
2208 }
2209
2210 // Permission granted to injection into all touched foreground windows.
2211 injectionPermission = INJECTION_PERMISSION_GRANTED;
2212 }
2213
2214 // Check whether windows listening for outside touches are owned by the same UID. If it is
2215 // set the policy flag that we will not reveal coordinate information to this window.
2216 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2217 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002219 if (foregroundWindowHandle) {
2220 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002221 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2223 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2224 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002225 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2226 InputTarget::FLAG_ZERO_COORDS,
2227 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230 }
2231 }
2232 }
2233
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 // If this is the first pointer going down and the touched window has a wallpaper
2235 // then also add the touched wallpaper windows so they are locked in for the duration
2236 // of the touch gesture.
2237 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2238 // engine only supports touch events. We would need to add a mechanism similar
2239 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2240 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2241 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002243 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002244 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002245 getWindowHandlesLocked(displayId);
2246 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002249 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002251 .addOrUpdateWindow(windowHandle,
2252 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2253 InputTarget::
2254 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2255 InputTarget::FLAG_DISPATCH_AS_IS,
2256 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
2258 }
2259 }
2260 }
2261
2262 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002263 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002265 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002270 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002271 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002273 }
2274
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 // Drop the outside or hover touch windows since we will not care about them
2276 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002277 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278
2279Failed:
2280 // Check injection permission once and for all.
2281 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002282 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 injectionPermission = INJECTION_PERMISSION_GRANTED;
2284 } else {
2285 injectionPermission = INJECTION_PERMISSION_DENIED;
2286 }
2287 }
2288
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002289 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2290 return injectionResult;
2291 }
2292
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002294 if (!wrongDevice) {
2295 if (switchedDevice) {
2296 if (DEBUG_FOCUS) {
2297 ALOGD("Conflicting pointer actions: Switched to a different device.");
2298 }
2299 *outConflictingPointerActions = true;
2300 }
2301
2302 if (isHoverAction) {
2303 // Started hovering, therefore no longer down.
2304 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002305 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002306 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2307 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 *outConflictingPointerActions = true;
2310 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002311 tempTouchState.reset();
2312 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2313 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2314 tempTouchState.deviceId = entry.deviceId;
2315 tempTouchState.source = entry.source;
2316 tempTouchState.displayId = displayId;
2317 }
2318 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2319 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2320 // All pointers up or canceled.
2321 tempTouchState.reset();
2322 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2323 // First pointer went down.
2324 if (oldState && oldState->down) {
2325 if (DEBUG_FOCUS) {
2326 ALOGD("Conflicting pointer actions: Down received while already down.");
2327 }
2328 *outConflictingPointerActions = true;
2329 }
2330 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2331 // One pointer went up.
2332 if (isSplit) {
2333 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2334 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002336 for (size_t i = 0; i < tempTouchState.windows.size();) {
2337 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2338 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2339 touchedWindow.pointerIds.clearBit(pointerId);
2340 if (touchedWindow.pointerIds.isEmpty()) {
2341 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2342 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002345 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002347 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002348 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002349
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002350 // Save changes unless the action was scroll in which case the temporary touch
2351 // state was only valid for this one action.
2352 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2353 if (tempTouchState.displayId >= 0) {
2354 mTouchStatesByDisplay[displayId] = tempTouchState;
2355 } else {
2356 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002360 // Update hover state.
2361 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 }
2363
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 return injectionResult;
2365}
2366
arthurhung6d4bed92021-03-17 11:59:33 +08002367void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2368 const sp<InputWindowHandle> dropWindow =
2369 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2370 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2371 true /*ignoreDragWindow*/);
2372 if (dropWindow) {
2373 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2374 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002375 } else {
2376 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002377 }
2378 mDragState.reset();
2379}
2380
2381void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2382 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002383 return;
2384 }
2385
arthurhung6d4bed92021-03-17 11:59:33 +08002386 if (!mDragState->isStartDrag) {
2387 mDragState->isStartDrag = true;
2388 mDragState->isStylusButtonDownAtStart =
2389 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2390 }
2391
arthurhungb89ccb02020-12-30 16:19:01 +08002392 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2393 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2394 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2395 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002396 // Handle the special case : stylus button no longer pressed.
2397 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2398 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2399 finishDragAndDrop(entry.displayId, x, y);
2400 return;
2401 }
2402
arthurhungb89ccb02020-12-30 16:19:01 +08002403 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002404 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002405 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2406 true /*ignoreDragWindow*/);
2407 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002408 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2409 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2410 if (mDragState->dragHoverWindowHandle != nullptr) {
2411 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2412 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002413 }
arthurhung6d4bed92021-03-17 11:59:33 +08002414 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002415 }
2416 // enqueue drag location if needed.
2417 if (hoverWindowHandle != nullptr) {
2418 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2419 }
arthurhung6d4bed92021-03-17 11:59:33 +08002420 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2421 finishDragAndDrop(entry.displayId, x, y);
2422 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002423 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002424 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002425 }
2426}
2427
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 int32_t targetFlags, BitSet32 pointerIds,
2430 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002431 std::vector<InputTarget>::iterator it =
2432 std::find_if(inputTargets.begin(), inputTargets.end(),
2433 [&windowHandle](const InputTarget& inputTarget) {
2434 return inputTarget.inputChannel->getConnectionToken() ==
2435 windowHandle->getToken();
2436 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002437
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002438 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439
2440 if (it == inputTargets.end()) {
2441 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002442 std::shared_ptr<InputChannel> inputChannel =
2443 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002444 if (inputChannel == nullptr) {
2445 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2446 return;
2447 }
2448 inputTarget.inputChannel = inputChannel;
2449 inputTarget.flags = targetFlags;
2450 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002451 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002452 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002453 inputTargets.push_back(inputTarget);
2454 it = inputTargets.end() - 1;
2455 }
2456
2457 ALOG_ASSERT(it->flags == targetFlags);
2458 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2459
chaviw1ff3d1e2020-07-01 15:53:47 -07002460 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461}
2462
Michael Wright3dd60e22019-03-27 22:06:44 +00002463void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002464 int32_t displayId, float xOffset,
2465 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002466 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2467 mGlobalMonitorsByDisplay.find(displayId);
2468
2469 if (it != mGlobalMonitorsByDisplay.end()) {
2470 const std::vector<Monitor>& monitors = it->second;
2471 for (const Monitor& monitor : monitors) {
2472 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 }
2475}
2476
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002477void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2478 float yOffset,
2479 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002480 InputTarget target;
2481 target.inputChannel = monitor.inputChannel;
2482 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002483 ui::Transform t;
2484 t.set(xOffset, yOffset);
2485 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002486 inputTargets.push_back(target);
2487}
2488
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490 const InjectionState* injectionState) {
2491 if (injectionState &&
2492 (windowHandle == nullptr ||
2493 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2494 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002495 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497 "owned by uid %d",
2498 injectionState->injectorPid, injectionState->injectorUid,
2499 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 } else {
2501 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 }
2504 return false;
2505 }
2506 return true;
2507}
2508
Robert Carrc9bf1d32020-04-13 17:21:08 -07002509/**
2510 * Indicate whether one window handle should be considered as obscuring
2511 * another window handle. We only check a few preconditions. Actually
2512 * checking the bounds is left to the caller.
2513 */
2514static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2515 const sp<InputWindowHandle>& otherHandle) {
2516 // Compare by token so cloned layers aren't counted
2517 if (haveSameToken(windowHandle, otherHandle)) {
2518 return false;
2519 }
2520 auto info = windowHandle->getInfo();
2521 auto otherInfo = otherHandle->getInfo();
2522 if (!otherInfo->visible) {
2523 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002524 } else if (otherInfo->alpha == 0 &&
2525 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2526 // Those act as if they were invisible, so we don't need to flag them.
2527 // We do want to potentially flag touchable windows even if they have 0
2528 // opacity, since they can consume touches and alter the effects of the
2529 // user interaction (eg. apps that rely on
2530 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2531 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2532 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002533 } else if (info->ownerUid == otherInfo->ownerUid) {
2534 // If ownerUid is the same we don't generate occlusion events as there
2535 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002536 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002537 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002538 return false;
2539 } else if (otherInfo->displayId != info->displayId) {
2540 return false;
2541 }
2542 return true;
2543}
2544
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002545/**
2546 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2547 * untrusted, one should check:
2548 *
2549 * 1. If result.hasBlockingOcclusion is true.
2550 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2551 * BLOCK_UNTRUSTED.
2552 *
2553 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2554 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2555 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2556 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2557 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2558 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2559 *
2560 * If neither of those is true, then it means the touch can be allowed.
2561 */
2562InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2563 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002564 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2565 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002566 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2567 TouchOcclusionInfo info;
2568 info.hasBlockingOcclusion = false;
2569 info.obscuringOpacity = 0;
2570 info.obscuringUid = -1;
2571 std::map<int32_t, float> opacityByUid;
2572 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2573 if (windowHandle == otherHandle) {
2574 break; // All future windows are below us. Exit early.
2575 }
2576 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002577 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2578 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002579 if (DEBUG_TOUCH_OCCLUSION) {
2580 info.debugInfo.push_back(
2581 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2582 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002583 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2584 // we perform the checks below to see if the touch can be propagated or not based on the
2585 // window's touch occlusion mode
2586 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2587 info.hasBlockingOcclusion = true;
2588 info.obscuringUid = otherInfo->ownerUid;
2589 info.obscuringPackage = otherInfo->packageName;
2590 break;
2591 }
2592 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2593 uint32_t uid = otherInfo->ownerUid;
2594 float opacity =
2595 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2596 // Given windows A and B:
2597 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2598 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2599 opacityByUid[uid] = opacity;
2600 if (opacity > info.obscuringOpacity) {
2601 info.obscuringOpacity = opacity;
2602 info.obscuringUid = uid;
2603 info.obscuringPackage = otherInfo->packageName;
2604 }
2605 }
2606 }
2607 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002608 if (DEBUG_TOUCH_OCCLUSION) {
2609 info.debugInfo.push_back(
2610 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2611 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002612 return info;
2613}
2614
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002615std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2616 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002617 return StringPrintf(INDENT2
2618 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2619 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2620 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2621 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002622 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002623 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002624 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002625 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2626 info->frameTop, info->frameRight, info->frameBottom,
2627 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002628 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2629 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2630 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002631}
2632
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002633bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2634 if (occlusionInfo.hasBlockingOcclusion) {
2635 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2636 occlusionInfo.obscuringUid);
2637 return false;
2638 }
2639 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2640 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2641 "%.2f, maximum allowed = %.2f)",
2642 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2643 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2644 return false;
2645 }
2646 return true;
2647}
2648
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002649bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2650 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002652 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002653 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002654 if (windowHandle == otherHandle) {
2655 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002658 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002659 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 return true;
2661 }
2662 }
2663 return false;
2664}
2665
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002666bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2667 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002668 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002669 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002670 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002671 if (windowHandle == otherHandle) {
2672 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002673 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002674 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002675 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002676 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002677 return true;
2678 }
2679 }
2680 return false;
2681}
2682
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002683std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002684 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002686 if (applicationHandle != nullptr) {
2687 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002688 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 } else {
2690 return applicationHandle->getName();
2691 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002692 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002693 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002695 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 }
2697}
2698
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002699void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002700 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002701 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2702 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002703 // Focus or pointer capture changed events are passed to apps, but do not represent user
2704 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002705 return;
2706 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002707 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002708 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002709 if (focusedWindowHandle != nullptr) {
2710 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002711 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002713 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714#endif
2715 return;
2716 }
2717 }
2718
2719 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002720 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002721 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002722 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2723 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 return;
2725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002727 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 eventType = USER_ACTIVITY_EVENT_TOUCH;
2729 }
2730 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002732 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002733 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2734 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 return;
2736 }
2737 eventType = USER_ACTIVITY_EVENT_BUTTON;
2738 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002740 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002741 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002742 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002743 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002744 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2745 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002746 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002747 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002748 break;
2749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 }
2751
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002752 std::unique_ptr<CommandEntry> commandEntry =
2753 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002754 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002756 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002757 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758}
2759
2760void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002762 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002763 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002764 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002766 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002767 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002768 ATRACE_NAME(message.c_str());
2769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770#if DEBUG_DISPATCH_CYCLE
2771 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002772 "globalScaleFactor=%f, pointerIds=0x%x %s",
2773 connection->getInputChannelName().c_str(), inputTarget.flags,
2774 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2775 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776#endif
2777
2778 // Skip this event if the connection status is not normal.
2779 // We don't want to enqueue additional outbound events if the connection is broken.
2780 if (connection->status != Connection::STATUS_NORMAL) {
2781#if DEBUG_DISPATCH_CYCLE
2782 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784#endif
2785 return;
2786 }
2787
2788 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002789 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2790 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2791 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002792 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002794 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002795 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002796 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002797 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 if (!splitMotionEntry) {
2799 return; // split event was dropped
2800 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002801 if (DEBUG_FOCUS) {
2802 ALOGD("channel '%s' ~ Split motion event.",
2803 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002804 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002805 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002806 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2807 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 return;
2809 }
2810 }
2811
2812 // Not splitting. Enqueue dispatch entries for the event as is.
2813 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2814}
2815
2816void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002818 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002819 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002820 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002822 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002823 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002824 ATRACE_NAME(message.c_str());
2825 }
2826
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002827 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828
2829 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002830 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002831 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002832 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002834 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002836 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002840 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842
2843 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002844 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 startDispatchCycleLocked(currentTime, connection);
2846 }
2847}
2848
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002850 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002851 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002852 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002853 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2855 connection->getInputChannelName().c_str(),
2856 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002857 ATRACE_NAME(message.c_str());
2858 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002859 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 if (!(inputTargetFlags & dispatchMode)) {
2861 return;
2862 }
2863 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2864
2865 // This is a new event.
2866 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002867 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002868 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2871 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002872 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002874 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002875 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002876 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002877 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002878 dispatchEntry->resolvedAction = keyEntry.action;
2879 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2882 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2885 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002887 return; // skip the inconsistent event
2888 }
2889 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002892 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002893 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002894 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2895 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2896 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2897 static_cast<int32_t>(IdGenerator::Source::OTHER);
2898 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2900 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2901 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2902 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2903 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2904 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2905 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2906 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2907 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2908 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2909 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002910 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002911 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 }
2913 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002914 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2915 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2918 "event",
2919 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002921 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2922 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2928 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2929 }
2930 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2931 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2935 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002937 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2938 "event",
2939 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 return; // skip the inconsistent event
2942 }
2943
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002944 dispatchEntry->resolvedEventId =
2945 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2946 ? mIdGenerator.nextId()
2947 : motionEntry.id;
2948 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2949 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2950 ") to MotionEvent(id=0x%" PRIx32 ").",
2951 motionEntry.id, dispatchEntry->resolvedEventId);
2952 ATRACE_NAME(message.c_str());
2953 }
2954
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002955 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2956 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2957 // Skip reporting pointer down outside focus to the policy.
2958 break;
2959 }
2960
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002961 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002962 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963
2964 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002966 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002967 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2968 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002969 break;
2970 }
Chris Yef59a2f42020-10-16 12:55:26 -07002971 case EventEntry::Type::SENSOR: {
2972 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2973 break;
2974 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002975 case EventEntry::Type::CONFIGURATION_CHANGED:
2976 case EventEntry::Type::DEVICE_RESET: {
2977 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002978 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002979 break;
2980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981 }
2982
2983 // Remember that we are waiting for this dispatch to complete.
2984 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002985 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 }
2987
2988 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002989 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002990 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002991}
2992
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002993/**
2994 * This function is purely for debugging. It helps us understand where the user interaction
2995 * was taking place. For example, if user is touching launcher, we will see a log that user
2996 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2997 * We will see both launcher and wallpaper in that list.
2998 * Once the interaction with a particular set of connections starts, no new logs will be printed
2999 * until the set of interacted connections changes.
3000 *
3001 * The following items are skipped, to reduce the logspam:
3002 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3003 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3004 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3005 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3006 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003007 */
3008void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3009 const std::vector<InputTarget>& targets) {
3010 // Skip ACTION_UP events, and all events other than keys and motions
3011 if (entry.type == EventEntry::Type::KEY) {
3012 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3013 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3014 return;
3015 }
3016 } else if (entry.type == EventEntry::Type::MOTION) {
3017 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3018 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3019 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3020 return;
3021 }
3022 } else {
3023 return; // Not a key or a motion
3024 }
3025
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003026 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003027 std::vector<sp<Connection>> newConnections;
3028 for (const InputTarget& target : targets) {
3029 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3030 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3031 continue; // Skip windows that receive ACTION_OUTSIDE
3032 }
3033
3034 sp<IBinder> token = target.inputChannel->getConnectionToken();
3035 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003036 if (connection == nullptr) {
3037 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003038 }
3039 newConnectionTokens.insert(std::move(token));
3040 newConnections.emplace_back(connection);
3041 }
3042 if (newConnectionTokens == mInteractionConnectionTokens) {
3043 return; // no change
3044 }
3045 mInteractionConnectionTokens = newConnectionTokens;
3046
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003047 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003048 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003049 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003050 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003051 std::string message = "Interaction with: " + targetList;
3052 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003053 message += "<none>";
3054 }
3055 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3056}
3057
chaviwfd6d3512019-03-25 13:23:49 -07003058void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003059 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003060 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003061 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3062 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003063 return;
3064 }
3065
Vishnu Nairc519ff72021-01-21 08:23:08 -08003066 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003067 if (focusedToken == token) {
3068 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003069 return;
3070 }
3071
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003072 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3073 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003074 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003075 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076}
3077
3078void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003080 if (ATRACE_ENABLED()) {
3081 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003082 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003083 ATRACE_NAME(message.c_str());
3084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087#endif
3088
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003089 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3090 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003092 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003093 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003094 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095
3096 // Publish the event.
3097 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003098 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3099 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003100 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003101 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3102 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 status = connection->inputPublisher
3106 .publishKeyEvent(dispatchEntry->seq,
3107 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3108 keyEntry.source, keyEntry.displayId,
3109 std::move(hmac), dispatchEntry->resolvedAction,
3110 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3111 keyEntry.scanCode, keyEntry.metaState,
3112 keyEntry.repeatCount, keyEntry.downTime,
3113 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
3116
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003117 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003118 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003121 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122
chaviw82357092020-01-28 13:13:06 -08003123 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003124 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3126 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003127 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003128 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3129 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003130 // Don't apply window scale here since we don't want scale to affect raw
3131 // coordinates. The scale will be sent back to the client and applied
3132 // later when requesting relative coordinates.
3133 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3134 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 }
3136 usingCoords = scaledCoords;
3137 }
3138 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 // We don't want the dispatch target to know.
3140 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003141 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 scaledCoords[i].clear();
3143 }
3144 usingCoords = scaledCoords;
3145 }
3146 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003147
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003148 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149
3150 // Publish the motion event.
3151 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003152 .publishMotionEvent(dispatchEntry->seq,
3153 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003154 motionEntry.deviceId, motionEntry.source,
3155 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003156 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003157 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003159 motionEntry.edgeFlags, motionEntry.metaState,
3160 motionEntry.buttonState,
3161 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003162 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 motionEntry.xPrecision, motionEntry.yPrecision,
3164 motionEntry.xCursorPosition,
3165 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003166 dispatchEntry->displaySize.x,
3167 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003168 motionEntry.downTime, motionEntry.eventTime,
3169 motionEntry.pointerCount,
3170 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 break;
3172 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003173
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003174 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003175 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003176 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003177 focusEntry.id,
3178 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003179 mInTouchMode);
3180 break;
3181 }
3182
Prabir Pradhan99987712020-11-10 18:43:05 -08003183 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3184 const auto& captureEntry =
3185 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3186 status = connection->inputPublisher
3187 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3188 captureEntry.pointerCaptureEnabled);
3189 break;
3190 }
3191
arthurhungb89ccb02020-12-30 16:19:01 +08003192 case EventEntry::Type::DRAG: {
3193 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3194 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3195 dragEntry.id, dragEntry.x,
3196 dragEntry.y,
3197 dragEntry.isExiting);
3198 break;
3199 }
3200
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003201 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003202 case EventEntry::Type::DEVICE_RESET:
3203 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003204 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003205 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003206 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 }
3209
3210 // Check the result.
3211 if (status) {
3212 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003213 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 "This is unexpected because the wait queue is empty, so the pipe "
3216 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003217 "event to it, status=%s(%d)",
3218 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3219 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3221 } else {
3222 // Pipe is full and we are waiting for the app to finish process some events
3223 // before sending more events to it.
3224#if DEBUG_DISPATCH_CYCLE
3225 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 "waiting for the application to catch up",
3227 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 }
3230 } else {
3231 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003232 "status=%s(%d)",
3233 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3234 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3236 }
3237 return;
3238 }
3239
3240 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003241 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3242 connection->outboundQueue.end(),
3243 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003244 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003245 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003246 if (connection->responsive) {
3247 mAnrTracker.insert(dispatchEntry->timeoutTime,
3248 connection->inputChannel->getConnectionToken());
3249 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003250 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 }
3252}
3253
chaviw09c8d2d2020-08-24 15:48:26 -07003254std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3255 size_t size;
3256 switch (event.type) {
3257 case VerifiedInputEvent::Type::KEY: {
3258 size = sizeof(VerifiedKeyEvent);
3259 break;
3260 }
3261 case VerifiedInputEvent::Type::MOTION: {
3262 size = sizeof(VerifiedMotionEvent);
3263 break;
3264 }
3265 }
3266 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3267 return mHmacKeyManager.sign(start, size);
3268}
3269
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003270const std::array<uint8_t, 32> InputDispatcher::getSignature(
3271 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3272 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3273 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3274 // Only sign events up and down events as the purely move events
3275 // are tied to their up/down counterparts so signing would be redundant.
3276 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3277 verifiedEvent.actionMasked = actionMasked;
3278 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003279 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003280 }
3281 return INVALID_HMAC;
3282}
3283
3284const std::array<uint8_t, 32> InputDispatcher::getSignature(
3285 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3286 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3287 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3288 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003289 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003290}
3291
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003294 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295#if DEBUG_DISPATCH_CYCLE
3296 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298#endif
3299
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 if (connection->status == Connection::STATUS_BROKEN ||
3301 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 return;
3303 }
3304
3305 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003306 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307}
3308
3309void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310 const sp<Connection>& connection,
3311 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312#if DEBUG_DISPATCH_CYCLE
3313 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315#endif
3316
3317 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003318 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003319 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003320 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003321 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
3323 // The connection appears to be unrecoverably broken.
3324 // Ignore already broken or zombie connections.
3325 if (connection->status == Connection::STATUS_NORMAL) {
3326 connection->status = Connection::STATUS_BROKEN;
3327
3328 if (notify) {
3329 // Notify other system components.
3330 onDispatchCycleBrokenLocked(currentTime, connection);
3331 }
3332 }
3333}
3334
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003335void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3336 while (!queue.empty()) {
3337 DispatchEntry* dispatchEntry = queue.front();
3338 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003339 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
3341}
3342
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003343void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003345 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 }
3347 delete dispatchEntry;
3348}
3349
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003350int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3351 std::scoped_lock _l(mLock);
3352 sp<Connection> connection = getConnectionLocked(connectionToken);
3353 if (connection == nullptr) {
3354 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3355 connectionToken.get(), events);
3356 return 0; // remove the callback
3357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003359 bool notify;
3360 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3361 if (!(events & ALOOPER_EVENT_INPUT)) {
3362 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3363 "events=0x%x",
3364 connection->getInputChannelName().c_str(), events);
3365 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 }
3367
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003368 nsecs_t currentTime = now();
3369 bool gotOne = false;
3370 status_t status = OK;
3371 for (;;) {
3372 Result<InputPublisher::ConsumerResponse> result =
3373 connection->inputPublisher.receiveConsumerResponse();
3374 if (!result.ok()) {
3375 status = result.error().code();
3376 break;
3377 }
3378
3379 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3380 const InputPublisher::Finished& finish =
3381 std::get<InputPublisher::Finished>(*result);
3382 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3383 finish.consumeTime);
3384 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003385 if (shouldReportMetricsForConnection(*connection)) {
3386 const InputPublisher::Timeline& timeline =
3387 std::get<InputPublisher::Timeline>(*result);
3388 mLatencyTracker
3389 .trackGraphicsLatency(timeline.inputEventId,
3390 connection->inputChannel->getConnectionToken(),
3391 std::move(timeline.graphicsTimeline));
3392 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003393 }
3394 gotOne = true;
3395 }
3396 if (gotOne) {
3397 runCommandsLockedInterruptible();
3398 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 return 1;
3400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 }
3402
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003403 notify = status != DEAD_OBJECT || !connection->monitor;
3404 if (notify) {
3405 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3406 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3407 status);
3408 }
3409 } else {
3410 // Monitor channels are never explicitly unregistered.
3411 // We do it automatically when the remote endpoint is closed so don't warn about them.
3412 const bool stillHaveWindowHandle =
3413 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3414 notify = !connection->monitor && stillHaveWindowHandle;
3415 if (notify) {
3416 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3417 connection->getInputChannelName().c_str(), events);
3418 }
3419 }
3420
3421 // Remove the channel.
3422 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3423 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424}
3425
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003426void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003428 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003429 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 }
3431}
3432
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003433void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003434 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003435 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3436 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3437}
3438
3439void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3440 const CancelationOptions& options,
3441 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3442 for (const auto& it : monitorsByDisplay) {
3443 const std::vector<Monitor>& monitors = it.second;
3444 for (const Monitor& monitor : monitors) {
3445 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003446 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003447 }
3448}
3449
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003451 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003452 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003453 if (connection == nullptr) {
3454 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003456
3457 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458}
3459
3460void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3461 const sp<Connection>& connection, const CancelationOptions& options) {
3462 if (connection->status == Connection::STATUS_BROKEN) {
3463 return;
3464 }
3465
3466 nsecs_t currentTime = now();
3467
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003468 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003469 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003471 if (cancelationEvents.empty()) {
3472 return;
3473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003475 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3476 "with reality: %s, mode=%d.",
3477 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3478 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003480
3481 InputTarget target;
3482 sp<InputWindowHandle> windowHandle =
3483 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3484 if (windowHandle != nullptr) {
3485 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003486 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003487 target.globalScaleFactor = windowInfo->globalScaleFactor;
3488 }
3489 target.inputChannel = connection->inputChannel;
3490 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3491
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003492 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003493 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003494 switch (cancelationEventEntry->type) {
3495 case EventEntry::Type::KEY: {
3496 logOutboundKeyDetails("cancel - ",
3497 static_cast<const KeyEntry&>(*cancelationEventEntry));
3498 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003500 case EventEntry::Type::MOTION: {
3501 logOutboundMotionDetails("cancel - ",
3502 static_cast<const MotionEntry&>(*cancelationEventEntry));
3503 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003505 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003506 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3507 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003508 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003509 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003510 break;
3511 }
3512 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003513 case EventEntry::Type::DEVICE_RESET:
3514 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003515 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003516 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003517 break;
3518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 }
3520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003521 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3522 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003524
3525 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526}
3527
Svet Ganov5d3bc372020-01-26 23:11:07 -08003528void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3529 const sp<Connection>& connection) {
3530 if (connection->status == Connection::STATUS_BROKEN) {
3531 return;
3532 }
3533
3534 nsecs_t currentTime = now();
3535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003536 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003537 connection->inputState.synthesizePointerDownEvents(currentTime);
3538
3539 if (downEvents.empty()) {
3540 return;
3541 }
3542
3543#if DEBUG_OUTBOUND_EVENT_DETAILS
3544 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3545 connection->getInputChannelName().c_str(), downEvents.size());
3546#endif
3547
3548 InputTarget target;
3549 sp<InputWindowHandle> windowHandle =
3550 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3551 if (windowHandle != nullptr) {
3552 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003553 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003554 target.globalScaleFactor = windowInfo->globalScaleFactor;
3555 }
3556 target.inputChannel = connection->inputChannel;
3557 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3558
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003559 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003560 switch (downEventEntry->type) {
3561 case EventEntry::Type::MOTION: {
3562 logOutboundMotionDetails("down - ",
3563 static_cast<const MotionEntry&>(*downEventEntry));
3564 break;
3565 }
3566
3567 case EventEntry::Type::KEY:
3568 case EventEntry::Type::FOCUS:
3569 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003570 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003571 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003572 case EventEntry::Type::SENSOR:
3573 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003574 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003575 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003576 break;
3577 }
3578 }
3579
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003580 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3581 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582 }
3583
3584 startDispatchCycleLocked(currentTime, connection);
3585}
3586
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003587std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3588 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 ALOG_ASSERT(pointerIds.value != 0);
3590
3591 uint32_t splitPointerIndexMap[MAX_POINTERS];
3592 PointerProperties splitPointerProperties[MAX_POINTERS];
3593 PointerCoords splitPointerCoords[MAX_POINTERS];
3594
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003595 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 uint32_t splitPointerCount = 0;
3597
3598 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003599 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003601 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 uint32_t pointerId = uint32_t(pointerProperties.id);
3603 if (pointerIds.hasBit(pointerId)) {
3604 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3605 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3606 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003607 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 splitPointerCount += 1;
3609 }
3610 }
3611
3612 if (splitPointerCount != pointerIds.count()) {
3613 // This is bad. We are missing some of the pointers that we expected to deliver.
3614 // Most likely this indicates that we received an ACTION_MOVE events that has
3615 // different pointer ids than we expected based on the previous ACTION_DOWN
3616 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3617 // in this way.
3618 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619 "we expected there to be %d pointers. This probably means we received "
3620 "a broken sequence of pointer ids from the input device.",
3621 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003622 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003625 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3628 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3630 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003631 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 uint32_t pointerId = uint32_t(pointerProperties.id);
3633 if (pointerIds.hasBit(pointerId)) {
3634 if (pointerIds.count() == 1) {
3635 // The first/last pointer went down/up.
3636 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003637 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003638 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3639 ? AMOTION_EVENT_ACTION_CANCEL
3640 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 } else {
3642 // A secondary pointer went down/up.
3643 uint32_t splitPointerIndex = 0;
3644 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3645 splitPointerIndex += 1;
3646 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 action = maskedAction |
3648 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
3650 } else {
3651 // An unrelated pointer changed.
3652 action = AMOTION_EVENT_ACTION_MOVE;
3653 }
3654 }
3655
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003656 int32_t newId = mIdGenerator.nextId();
3657 if (ATRACE_ENABLED()) {
3658 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3659 ") to MotionEvent(id=0x%" PRIx32 ").",
3660 originalMotionEntry.id, newId);
3661 ATRACE_NAME(message.c_str());
3662 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003663 std::unique_ptr<MotionEntry> splitMotionEntry =
3664 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3665 originalMotionEntry.deviceId, originalMotionEntry.source,
3666 originalMotionEntry.displayId,
3667 originalMotionEntry.policyFlags, action,
3668 originalMotionEntry.actionButton,
3669 originalMotionEntry.flags, originalMotionEntry.metaState,
3670 originalMotionEntry.buttonState,
3671 originalMotionEntry.classification,
3672 originalMotionEntry.edgeFlags,
3673 originalMotionEntry.xPrecision,
3674 originalMotionEntry.yPrecision,
3675 originalMotionEntry.xCursorPosition,
3676 originalMotionEntry.yCursorPosition,
3677 originalMotionEntry.downTime, splitPointerCount,
3678 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003680 if (originalMotionEntry.injectionState) {
3681 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 splitMotionEntry->injectionState->refCount += 1;
3683 }
3684
3685 return splitMotionEntry;
3686}
3687
3688void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3689#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003690 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691#endif
3692
3693 bool needWake;
3694 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003695 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003697 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3698 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3699 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 } // release lock
3701
3702 if (needWake) {
3703 mLooper->wake();
3704 }
3705}
3706
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003707/**
3708 * If one of the meta shortcuts is detected, process them here:
3709 * Meta + Backspace -> generate BACK
3710 * Meta + Enter -> generate HOME
3711 * This will potentially overwrite keyCode and metaState.
3712 */
3713void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003715 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3716 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3717 if (keyCode == AKEYCODE_DEL) {
3718 newKeyCode = AKEYCODE_BACK;
3719 } else if (keyCode == AKEYCODE_ENTER) {
3720 newKeyCode = AKEYCODE_HOME;
3721 }
3722 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003723 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003724 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003725 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003726 keyCode = newKeyCode;
3727 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3728 }
3729 } else if (action == AKEY_EVENT_ACTION_UP) {
3730 // In order to maintain a consistent stream of up and down events, check to see if the key
3731 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3732 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003733 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003734 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003735 auto replacementIt = mReplacedKeys.find(replacement);
3736 if (replacementIt != mReplacedKeys.end()) {
3737 keyCode = replacementIt->second;
3738 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003739 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3740 }
3741 }
3742}
3743
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3745#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003746 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3747 "policyFlags=0x%x, action=0x%x, "
3748 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3749 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3750 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3751 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752#endif
3753 if (!validateKeyEvent(args->action)) {
3754 return;
3755 }
3756
3757 uint32_t policyFlags = args->policyFlags;
3758 int32_t flags = args->flags;
3759 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003760 // InputDispatcher tracks and generates key repeats on behalf of
3761 // whatever notifies it, so repeatCount should always be set to 0
3762 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3764 policyFlags |= POLICY_FLAG_VIRTUAL;
3765 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 if (policyFlags & POLICY_FLAG_FUNCTION) {
3768 metaState |= AMETA_FUNCTION_ON;
3769 }
3770
3771 policyFlags |= POLICY_FLAG_TRUSTED;
3772
Michael Wright78f24442014-08-06 15:55:28 -07003773 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003774 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003775
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003777 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003778 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3779 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
Michael Wright2b3c3302018-03-02 17:19:13 +00003781 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003783 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3784 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 bool needWake;
3789 { // acquire lock
3790 mLock.lock();
3791
3792 if (shouldSendKeyToInputFilterLocked(args)) {
3793 mLock.unlock();
3794
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003795 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3797 return; // event was consumed by the filter
3798 }
3799
3800 mLock.lock();
3801 }
3802
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003803 std::unique_ptr<KeyEntry> newEntry =
3804 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3805 args->displayId, policyFlags, args->action, flags,
3806 keyCode, args->scanCode, metaState, repeatCount,
3807 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003809 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 mLock.unlock();
3811 } // release lock
3812
3813 if (needWake) {
3814 mLooper->wake();
3815 }
3816}
3817
3818bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3819 return mInputFilterEnabled;
3820}
3821
3822void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3823#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003824 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3825 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003826 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3827 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003828 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003829 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3830 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3831 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3832 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 for (uint32_t i = 0; i < args->pointerCount; i++) {
3834 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003835 "x=%f, y=%f, pressure=%f, size=%f, "
3836 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3837 "orientation=%f",
3838 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3839 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3840 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3841 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3842 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3843 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3844 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3845 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3846 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3847 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3851 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 return;
3853 }
3854
3855 uint32_t policyFlags = args->policyFlags;
3856 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003857
3858 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003859 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003860 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3861 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003862 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864
3865 bool needWake;
3866 { // acquire lock
3867 mLock.lock();
3868
3869 if (shouldSendMotionToInputFilterLocked(args)) {
3870 mLock.unlock();
3871
3872 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003873 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003874 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3875 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003876 args->metaState, args->buttonState, args->classification, transform,
3877 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003878 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3879 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003880 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881
3882 policyFlags |= POLICY_FLAG_FILTERED;
3883 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3884 return; // event was consumed by the filter
3885 }
3886
3887 mLock.lock();
3888 }
3889
3890 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003891 std::unique_ptr<MotionEntry> newEntry =
3892 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3893 args->source, args->displayId, policyFlags,
3894 args->action, args->actionButton, args->flags,
3895 args->metaState, args->buttonState,
3896 args->classification, args->edgeFlags,
3897 args->xPrecision, args->yPrecision,
3898 args->xCursorPosition, args->yCursorPosition,
3899 args->downTime, args->pointerCount,
3900 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
Siarhei Vishniakouf9cb2a72021-07-09 03:22:42 +00003902 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3903 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3904 !mInputFilterEnabled) {
3905 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3906 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3907 }
3908
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003909 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 mLock.unlock();
3911 } // release lock
3912
3913 if (needWake) {
3914 mLooper->wake();
3915 }
3916}
3917
Chris Yef59a2f42020-10-16 12:55:26 -07003918void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3919#if DEBUG_INBOUND_EVENT_DETAILS
3920 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3921 " sensorType=%s",
3922 args->id, args->eventTime, args->deviceId, args->source,
3923 NamedEnum::string(args->sensorType).c_str());
3924#endif
3925
3926 bool needWake;
3927 { // acquire lock
3928 mLock.lock();
3929
3930 // Just enqueue a new sensor event.
3931 std::unique_ptr<SensorEntry> newEntry =
3932 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3933 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3934 args->sensorType, args->accuracy,
3935 args->accuracyChanged, args->values);
3936
3937 needWake = enqueueInboundEventLocked(std::move(newEntry));
3938 mLock.unlock();
3939 } // release lock
3940
3941 if (needWake) {
3942 mLooper->wake();
3943 }
3944}
3945
Chris Yefb552902021-02-03 17:18:37 -08003946void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3947#if DEBUG_INBOUND_EVENT_DETAILS
3948 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3949 args->deviceId, args->isOn);
3950#endif
3951 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3952}
3953
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003955 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956}
3957
3958void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3959#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003960 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003961 "switchMask=0x%08x",
3962 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963#endif
3964
3965 uint32_t policyFlags = args->policyFlags;
3966 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968}
3969
3970void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3971#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003972 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3973 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974#endif
3975
3976 bool needWake;
3977 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003978 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003980 std::unique_ptr<DeviceResetEntry> newEntry =
3981 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3982 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 } // release lock
3984
3985 if (needWake) {
3986 mLooper->wake();
3987 }
3988}
3989
Prabir Pradhan7e186182020-11-10 13:56:45 -08003990void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3991#if DEBUG_INBOUND_EVENT_DETAILS
3992 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3993 args->enabled ? "true" : "false");
3994#endif
3995
Prabir Pradhan99987712020-11-10 18:43:05 -08003996 bool needWake;
3997 { // acquire lock
3998 std::scoped_lock _l(mLock);
3999 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
4000 args->enabled);
4001 needWake = enqueueInboundEventLocked(std::move(entry));
4002 } // release lock
4003
4004 if (needWake) {
4005 mLooper->wake();
4006 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004007}
4008
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004009InputEventInjectionResult InputDispatcher::injectInputEvent(
4010 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4011 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012#if DEBUG_INBOUND_EVENT_DETAILS
4013 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004014 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4015 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004017 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
4019 policyFlags |= POLICY_FLAG_INJECTED;
4020 if (hasInjectionPermission(injectorPid, injectorUid)) {
4021 policyFlags |= POLICY_FLAG_TRUSTED;
4022 }
4023
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004024 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004025 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4026 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4027 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4028 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4029 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004030 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004031 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004032 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004033 }
4034
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004035 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004037 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004038 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4039 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004041 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004044 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004045 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4046 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4047 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004048 int32_t keyCode = incomingKey.getKeyCode();
4049 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004050 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004051 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004052 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004053 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004054 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4055 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4056 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4059 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004060 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061
4062 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4063 android::base::Timer t;
4064 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4065 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4066 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4067 std::to_string(t.duration().count()).c_str());
4068 }
4069 }
4070
4071 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004072 std::unique_ptr<KeyEntry> injectedEntry =
4073 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004074 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004075 incomingKey.getDisplayId(), policyFlags, action,
4076 flags, keyCode, incomingKey.getScanCode(), metaState,
4077 incomingKey.getRepeatCount(),
4078 incomingKey.getDownTime());
4079 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 }
4082
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004084 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4085 int32_t action = motionEvent.getAction();
4086 size_t pointerCount = motionEvent.getPointerCount();
4087 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4088 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004089 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004090 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004091 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004092 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 }
4094
4095 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004096 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 android::base::Timer t;
4098 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4099 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4100 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4101 std::to_string(t.duration().count()).c_str());
4102 }
4103 }
4104
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004105 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4106 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4107 }
4108
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004109 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004110 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4111 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004112 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004113 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4114 resolvedDeviceId, motionEvent.getSource(),
4115 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004116 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004117 motionEvent.getButtonState(),
4118 motionEvent.getClassification(),
4119 motionEvent.getEdgeFlags(),
4120 motionEvent.getXPrecision(),
4121 motionEvent.getYPrecision(),
4122 motionEvent.getRawXCursorPosition(),
4123 motionEvent.getRawYCursorPosition(),
4124 motionEvent.getDownTime(), uint32_t(pointerCount),
4125 pointerProperties, samplePointerCoords,
4126 motionEvent.getXOffset(),
4127 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004128 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004129 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 sampleEventTimes += 1;
4131 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004132 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004133 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4134 resolvedDeviceId, motionEvent.getSource(),
4135 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004136 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 motionEvent.getMetaState(),
4138 motionEvent.getButtonState(),
4139 motionEvent.getClassification(),
4140 motionEvent.getEdgeFlags(),
4141 motionEvent.getXPrecision(),
4142 motionEvent.getYPrecision(),
4143 motionEvent.getRawXCursorPosition(),
4144 motionEvent.getRawYCursorPosition(),
4145 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004147 samplePointerCoords, motionEvent.getXOffset(),
4148 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004149 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004150 }
4151 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004155 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004156 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 }
4158
4159 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004160 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 injectionState->injectionIsAsync = true;
4162 }
4163
4164 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004165 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166
4167 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004168 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004169 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004170 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172
4173 mLock.unlock();
4174
4175 if (needWake) {
4176 mLooper->wake();
4177 }
4178
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004181 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004183 if (syncMode == InputEventInjectionSync::NONE) {
4184 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 } else {
4186 for (;;) {
4187 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004188 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 break;
4190 }
4191
4192 nsecs_t remainingTimeout = endTime - now();
4193 if (remainingTimeout <= 0) {
4194#if DEBUG_INJECTION
4195 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004198 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 break;
4200 }
4201
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004202 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 }
4204
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004205 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4206 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 while (injectionState->pendingForegroundDispatches != 0) {
4208#if DEBUG_INJECTION
4209 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004210 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211#endif
4212 nsecs_t remainingTimeout = endTime - now();
4213 if (remainingTimeout <= 0) {
4214#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004215 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4216 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004218 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 break;
4220 }
4221
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004222 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224 }
4225 }
4226
4227 injectionState->release();
4228 } // release lock
4229
4230#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004231 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004232 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233#endif
4234
4235 return injectionResult;
4236}
4237
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004238std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004239 std::array<uint8_t, 32> calculatedHmac;
4240 std::unique_ptr<VerifiedInputEvent> result;
4241 switch (event.getType()) {
4242 case AINPUT_EVENT_TYPE_KEY: {
4243 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4244 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4245 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004246 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004247 break;
4248 }
4249 case AINPUT_EVENT_TYPE_MOTION: {
4250 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4251 VerifiedMotionEvent verifiedMotionEvent =
4252 verifiedMotionEventFromMotionEvent(motionEvent);
4253 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004254 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004255 break;
4256 }
4257 default: {
4258 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4259 return nullptr;
4260 }
4261 }
4262 if (calculatedHmac == INVALID_HMAC) {
4263 return nullptr;
4264 }
4265 if (calculatedHmac != event.getHmac()) {
4266 return nullptr;
4267 }
4268 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004269}
4270
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 return injectorUid == 0 ||
4273 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274}
4275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004277 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 if (injectionState) {
4280#if DEBUG_INJECTION
4281 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 "injectorPid=%d, injectorUid=%d",
4283 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284#endif
4285
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004286 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 // Log the outcome since the injector did not wait for the injection result.
4288 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004289 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290 ALOGV("Asynchronous input event injection succeeded.");
4291 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 ALOGW("Asynchronous input event injection failed.");
4294 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004295 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 ALOGW("Asynchronous input event injection permission denied.");
4297 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004298 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 ALOGW("Asynchronous input event injection timed out.");
4300 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 case InputEventInjectionResult::PENDING:
4302 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4303 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 }
4305 }
4306
4307 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004308 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 }
4310}
4311
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004312void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4313 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 if (injectionState) {
4315 injectionState->pendingForegroundDispatches += 1;
4316 }
4317}
4318
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4320 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 if (injectionState) {
4322 injectionState->pendingForegroundDispatches -= 1;
4323
4324 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004325 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 }
4327 }
4328}
4329
Vishnu Nairad321cd2020-08-20 16:40:21 -07004330const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004331 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004332 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4333 auto it = mWindowHandlesByDisplay.find(displayId);
4334 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004335}
4336
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004338 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004339 if (windowHandleToken == nullptr) {
4340 return nullptr;
4341 }
4342
Arthur Hungb92218b2018-08-14 12:00:21 +08004343 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004344 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004345 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004346 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004347 return windowHandle;
4348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 }
4350 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004351 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352}
4353
Vishnu Nairad321cd2020-08-20 16:40:21 -07004354sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4355 int displayId) const {
4356 if (windowHandleToken == nullptr) {
4357 return nullptr;
4358 }
4359
4360 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4361 if (windowHandle->getToken() == windowHandleToken) {
4362 return windowHandle;
4363 }
4364 }
4365 return nullptr;
4366}
4367
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004368sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4369 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004370 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004371 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004372 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004373 if (handle->getId() == windowHandle->getId() &&
4374 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004375 if (windowHandle->getInfo()->displayId != it.first) {
4376 ALOGE("Found window %s in display %" PRId32
4377 ", but it should belong to display %" PRId32,
4378 windowHandle->getName().c_str(), it.first,
4379 windowHandle->getInfo()->displayId);
4380 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004381 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 }
4384 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004385 return nullptr;
4386}
4387
4388sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4389 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4390 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391}
4392
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004393bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4394 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4395 const bool noInputChannel =
4396 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4397 if (connection != nullptr && noInputChannel) {
4398 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4399 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4400 return false;
4401 }
4402
4403 if (connection == nullptr) {
4404 if (!noInputChannel) {
4405 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4406 }
4407 return false;
4408 }
4409 if (!connection->responsive) {
4410 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4411 return false;
4412 }
4413 return true;
4414}
4415
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004416std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4417 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004418 auto connectionIt = mConnectionsByToken.find(token);
4419 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004420 return nullptr;
4421 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004422 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004423}
4424
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004425void InputDispatcher::updateWindowHandlesForDisplayLocked(
4426 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4427 if (inputWindowHandles.empty()) {
4428 // Remove all handles on a display if there are no windows left.
4429 mWindowHandlesByDisplay.erase(displayId);
4430 return;
4431 }
4432
4433 // Since we compare the pointer of input window handles across window updates, we need
4434 // to make sure the handle object for the same window stays unchanged across updates.
4435 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004436 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004437 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004438 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004439 }
4440
4441 std::vector<sp<InputWindowHandle>> newHandles;
4442 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4443 if (!handle->updateInfo()) {
4444 // handle no longer valid
4445 continue;
4446 }
4447
4448 const InputWindowInfo* info = handle->getInfo();
4449 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4450 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4451 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004452 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4453 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4454 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004455 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004456 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004457 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004458 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004459 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004460 }
4461
4462 if (info->displayId != displayId) {
4463 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4464 handle->getName().c_str(), displayId, info->displayId);
4465 continue;
4466 }
4467
Robert Carredd13602020-04-13 17:24:34 -07004468 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4469 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004470 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004471 oldHandle->updateFrom(handle);
4472 newHandles.push_back(oldHandle);
4473 } else {
4474 newHandles.push_back(handle);
4475 }
4476 }
4477
4478 // Insert or replace
4479 mWindowHandlesByDisplay[displayId] = newHandles;
4480}
4481
Arthur Hung72d8dc32020-03-28 00:48:39 +00004482void InputDispatcher::setInputWindows(
4483 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4484 { // acquire lock
4485 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004486 for (const auto& [displayId, handles] : handlesPerDisplay) {
4487 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004488 }
4489 }
4490 // Wake up poll loop since it may need to make new input dispatching choices.
4491 mLooper->wake();
4492}
4493
Arthur Hungb92218b2018-08-14 12:00:21 +08004494/**
4495 * Called from InputManagerService, update window handle list by displayId that can receive input.
4496 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4497 * If set an empty list, remove all handles from the specific display.
4498 * For focused handle, check if need to change and send a cancel event to previous one.
4499 * For removed handle, check if need to send a cancel event if already in touch.
4500 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004501void InputDispatcher::setInputWindowsLocked(
4502 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004503 if (DEBUG_FOCUS) {
4504 std::string windowList;
4505 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4506 windowList += iwh->getName() + " ";
4507 }
4508 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004511 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4512 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4513 const bool noInputWindow =
4514 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4515 if (noInputWindow && window->getToken() != nullptr) {
4516 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4517 window->getName().c_str());
4518 window->releaseChannel();
4519 }
4520 }
4521
Arthur Hung72d8dc32020-03-28 00:48:39 +00004522 // Copy old handles for release if they are no longer present.
4523 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004525 // Save the old windows' orientation by ID before it gets updated.
4526 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4527 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4528 oldWindowOrientations.emplace(handle->getId(),
4529 handle->getInfo()->transform.getOrientation());
4530 }
4531
Arthur Hung72d8dc32020-03-28 00:48:39 +00004532 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004533
Vishnu Nair958da932020-08-21 17:12:37 -07004534 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4535 if (mLastHoverWindowHandle &&
4536 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4537 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004538 mLastHoverWindowHandle = nullptr;
4539 }
4540
Vishnu Nairc519ff72021-01-21 08:23:08 -08004541 std::optional<FocusResolver::FocusChanges> changes =
4542 mFocusResolver.setInputWindows(displayId, windowHandles);
4543 if (changes) {
4544 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004547 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4548 mTouchStatesByDisplay.find(displayId);
4549 if (stateIt != mTouchStatesByDisplay.end()) {
4550 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004551 for (size_t i = 0; i < state.windows.size();) {
4552 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004553 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004554 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004555 ALOGD("Touched window was removed: %s in display %" PRId32,
4556 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004557 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004558 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004559 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4560 if (touchedInputChannel != nullptr) {
4561 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4562 "touched window was removed");
4563 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004565 state.windows.erase(state.windows.begin() + i);
4566 } else {
4567 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 }
4569 }
arthurhungb89ccb02020-12-30 16:19:01 +08004570
arthurhung6d4bed92021-03-17 11:59:33 +08004571 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004572 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004573 if (mDragState &&
4574 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004575 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004576 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004577 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004578 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004579
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004580 if (isPerWindowInputRotationEnabled()) {
4581 // Determine if the orientation of any of the input windows have changed, and cancel all
4582 // pointer events if necessary.
4583 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4584 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4585 if (newWindowHandle != nullptr &&
4586 newWindowHandle->getInfo()->transform.getOrientation() !=
4587 oldWindowOrientations[oldWindowHandle->getId()]) {
4588 std::shared_ptr<InputChannel> inputChannel =
4589 getInputChannelLocked(newWindowHandle->getToken());
4590 if (inputChannel != nullptr) {
4591 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4592 "touched window's orientation changed");
4593 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4594 }
4595 }
4596 }
4597 }
4598
Arthur Hung72d8dc32020-03-28 00:48:39 +00004599 // Release information for windows that are no longer present.
4600 // This ensures that unused input channels are released promptly.
4601 // Otherwise, they might stick around until the window handle is destroyed
4602 // which might not happen until the next GC.
4603 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004604 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004605 if (DEBUG_FOCUS) {
4606 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004607 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004608 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004609 // To avoid making too many calls into the compat framework, only
4610 // check for window flags when windows are going away.
4611 // TODO(b/157929241) : delete this. This is only needed temporarily
4612 // in order to gather some data about the flag usage
4613 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4614 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4615 oldWindowHandle->getName().c_str());
4616 if (mCompatService != nullptr) {
4617 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4618 oldWindowHandle->getInfo()->ownerUid);
4619 }
4620 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004621 }
chaviw291d88a2019-02-14 10:33:58 -08004622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623}
4624
4625void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004626 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004627 if (DEBUG_FOCUS) {
4628 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4629 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4630 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004631 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004632 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004633 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 } // release lock
4635
4636 // Wake up poll loop since it may need to make new input dispatching choices.
4637 mLooper->wake();
4638}
4639
Vishnu Nair599f1412021-06-21 10:39:58 -07004640void InputDispatcher::setFocusedApplicationLocked(
4641 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4642 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4643 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4644
4645 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4646 return; // This application is already focused. No need to wake up or change anything.
4647 }
4648
4649 // Set the new application handle.
4650 if (inputApplicationHandle != nullptr) {
4651 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4652 } else {
4653 mFocusedApplicationHandlesByDisplay.erase(displayId);
4654 }
4655
4656 // No matter what the old focused application was, stop waiting on it because it is
4657 // no longer focused.
4658 resetNoFocusedWindowTimeoutLocked();
4659}
4660
Tiger Huang721e26f2018-07-24 22:26:19 +08004661/**
4662 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4663 * the display not specified.
4664 *
4665 * We track any unreleased events for each window. If a window loses the ability to receive the
4666 * released event, we will send a cancel event to it. So when the focused display is changed, we
4667 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4668 * display. The display-specified events won't be affected.
4669 */
4670void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004671 if (DEBUG_FOCUS) {
4672 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4673 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004674 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004675 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004676
4677 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004678 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004679 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004680 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004681 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004682 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004683 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004684 CancelationOptions
4685 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4686 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004687 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004688 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4689 }
4690 }
4691 mFocusedDisplayId = displayId;
4692
Chris Ye3c2d6f52020-08-09 10:39:48 -07004693 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004694 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004695 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004696
Vishnu Nairad321cd2020-08-20 16:40:21 -07004697 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004698 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004699 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004700 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004701 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004702 }
4703 }
4704 }
4705
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004706 if (DEBUG_FOCUS) {
4707 logDispatchStateLocked();
4708 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004709 } // release lock
4710
4711 // Wake up poll loop since it may need to make new input dispatching choices.
4712 mLooper->wake();
4713}
4714
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004716 if (DEBUG_FOCUS) {
4717 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719
4720 bool changed;
4721 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004722 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
4724 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4725 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004726 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 }
4728
4729 if (mDispatchEnabled && !enabled) {
4730 resetAndDropEverythingLocked("dispatcher is being disabled");
4731 }
4732
4733 mDispatchEnabled = enabled;
4734 mDispatchFrozen = frozen;
4735 changed = true;
4736 } else {
4737 changed = false;
4738 }
4739
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004740 if (DEBUG_FOCUS) {
4741 logDispatchStateLocked();
4742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 } // release lock
4744
4745 if (changed) {
4746 // Wake up poll loop since it may need to make new input dispatching choices.
4747 mLooper->wake();
4748 }
4749}
4750
4751void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004752 if (DEBUG_FOCUS) {
4753 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755
4756 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004757 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
4759 if (mInputFilterEnabled == enabled) {
4760 return;
4761 }
4762
4763 mInputFilterEnabled = enabled;
4764 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4765 } // release lock
4766
4767 // Wake up poll loop since there might be work to do to drop everything.
4768 mLooper->wake();
4769}
4770
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004771void InputDispatcher::setInTouchMode(bool inTouchMode) {
4772 std::scoped_lock lock(mLock);
4773 mInTouchMode = inTouchMode;
4774}
4775
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004776void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4777 if (opacity < 0 || opacity > 1) {
4778 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4779 return;
4780 }
4781
4782 std::scoped_lock lock(mLock);
4783 mMaximumObscuringOpacityForTouch = opacity;
4784}
4785
4786void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4787 std::scoped_lock lock(mLock);
4788 mBlockUntrustedTouchesMode = mode;
4789}
4790
arthurhungb89ccb02020-12-30 16:19:01 +08004791bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4792 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004793 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004794 if (DEBUG_FOCUS) {
4795 ALOGD("Trivial transfer to same window.");
4796 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004797 return true;
4798 }
4799
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004801 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802
chaviwfbe5d9c2018-12-26 12:23:37 -08004803 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4804 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004805 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004806 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 return false;
4808 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004809 if (DEBUG_FOCUS) {
4810 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4811 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004814 if (DEBUG_FOCUS) {
4815 ALOGD("Cannot transfer focus because windows are on different displays.");
4816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 return false;
4818 }
4819
4820 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004821 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4822 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004823 for (size_t i = 0; i < state.windows.size(); i++) {
4824 const TouchedWindow& touchedWindow = state.windows[i];
4825 if (touchedWindow.windowHandle == fromWindowHandle) {
4826 int32_t oldTargetFlags = touchedWindow.targetFlags;
4827 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004829 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004831 int32_t newTargetFlags = oldTargetFlags &
4832 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4833 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004834 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835
arthurhungb89ccb02020-12-30 16:19:01 +08004836 // Store the dragging window.
4837 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004838 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004839 }
4840
Jeff Brownf086ddb2014-02-11 14:28:48 -08004841 found = true;
4842 goto Found;
4843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 }
4845 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004846 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004848 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004849 if (DEBUG_FOCUS) {
4850 ALOGD("Focus transfer failed because from window did not have focus.");
4851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 return false;
4853 }
4854
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004855 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4856 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004857 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004858 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004859 CancelationOptions
4860 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4861 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004863 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 }
4865
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004866 if (DEBUG_FOCUS) {
4867 logDispatchStateLocked();
4868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 } // release lock
4870
4871 // Wake up poll loop since it may need to make new input dispatching choices.
4872 mLooper->wake();
4873 return true;
4874}
4875
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004876// Binder call
4877bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4878 sp<IBinder> fromToken;
4879 { // acquire lock
4880 std::scoped_lock _l(mLock);
4881
4882 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4883 if (toWindowHandle == nullptr) {
4884 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4885 return false;
4886 }
4887
4888 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4889
4890 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4891 if (touchStateIt == mTouchStatesByDisplay.end()) {
4892 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4893 displayId);
4894 return false;
4895 }
4896
4897 TouchState& state = touchStateIt->second;
4898 if (state.windows.size() != 1) {
4899 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4900 state.windows.size());
4901 return false;
4902 }
4903 const TouchedWindow& touchedWindow = state.windows[0];
4904 fromToken = touchedWindow.windowHandle->getToken();
4905 } // release lock
4906
4907 return transferTouchFocus(fromToken, destChannelToken);
4908}
4909
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004911 if (DEBUG_FOCUS) {
4912 ALOGD("Resetting and dropping all events (%s).", reason);
4913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
4915 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4916 synthesizeCancelationEventsForAllConnectionsLocked(options);
4917
4918 resetKeyRepeatLocked();
4919 releasePendingEventLocked();
4920 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004921 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004923 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004924 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004926 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927}
4928
4929void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004930 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931 dumpDispatchStateLocked(dump);
4932
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004933 std::istringstream stream(dump);
4934 std::string line;
4935
4936 while (std::getline(stream, line, '\n')) {
4937 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 }
4939}
4940
Prabir Pradhan99987712020-11-10 18:43:05 -08004941std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4942 std::string dump;
4943
4944 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4945 toString(mFocusedWindowRequestedPointerCapture));
4946
4947 std::string windowName = "None";
4948 if (mWindowTokenWithPointerCapture) {
4949 const sp<InputWindowHandle> captureWindowHandle =
4950 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4951 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4952 : "token has capture without window";
4953 }
4954 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4955
4956 return dump;
4957}
4958
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004959void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004960 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4961 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4962 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004963 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964
Tiger Huang721e26f2018-07-24 22:26:19 +08004965 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4966 dump += StringPrintf(INDENT "FocusedApplications:\n");
4967 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4968 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004969 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004970 const std::chrono::duration timeout =
4971 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004972 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004973 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004974 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004977 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004979
Vishnu Nairc519ff72021-01-21 08:23:08 -08004980 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004981 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004983 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004984 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004985 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4986 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004987 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004988 state.displayId, toString(state.down), toString(state.split),
4989 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004990 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004991 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004992 for (size_t i = 0; i < state.windows.size(); i++) {
4993 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004994 dump += StringPrintf(INDENT4
4995 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4996 i, touchedWindow.windowHandle->getName().c_str(),
4997 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004998 }
4999 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005000 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005001 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005002 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005003 dump += INDENT3 "Portal windows:\n";
5004 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005005 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005006 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5007 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005008 }
5009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010 }
5011 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005012 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 }
5014
arthurhung6d4bed92021-03-17 11:59:33 +08005015 if (mDragState) {
5016 dump += StringPrintf(INDENT "DragState:\n");
5017 mDragState->dump(dump, INDENT2);
5018 }
5019
Arthur Hungb92218b2018-08-14 12:00:21 +08005020 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005021 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005022 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005023 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005024 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005025 dump += INDENT2 "Windows:\n";
5026 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005027 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08005028 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005030 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005031 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005032 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005033 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005034 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005035 "applicationInfo.name=%s, "
5036 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005037 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005038 i, windowInfo->name.c_str(), windowInfo->id,
5039 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005040 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005041 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005042 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005043 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005044 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005045 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005046 windowInfo->frameLeft, windowInfo->frameTop,
5047 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005048 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005049 windowInfo->applicationInfo.name.c_str(),
5050 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005051 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005052 dump += StringPrintf(", inputFeatures=%s",
5053 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005054 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005055 "ms, trustedOverlay=%s, hasToken=%s, "
5056 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005057 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005058 millis(windowInfo->dispatchingTimeout),
5059 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005060 toString(windowInfo->token != nullptr),
5061 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005062 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005063 }
5064 } else {
5065 dump += INDENT2 "Windows: <none>\n";
5066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 }
5068 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005069 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005070 }
5071
Michael Wright3dd60e22019-03-27 22:06:44 +00005072 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005073 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005074 const std::vector<Monitor>& monitors = it.second;
5075 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5076 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005077 }
5078 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005079 const std::vector<Monitor>& monitors = it.second;
5080 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5081 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005084 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085 }
5086
5087 nsecs_t currentTime = now();
5088
5089 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005090 if (!mRecentQueue.empty()) {
5091 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005092 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005093 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005094 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005095 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 }
5097 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005098 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 }
5100
5101 // Dump event currently being dispatched.
5102 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005103 dump += INDENT "PendingEvent:\n";
5104 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005105 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005106 dump += StringPrintf(", age=%" PRId64 "ms\n",
5107 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005109 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
5111
5112 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005113 if (!mInboundQueue.empty()) {
5114 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005115 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005116 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005117 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005118 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 }
5120 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005121 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122 }
5123
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005124 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005125 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005126 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5127 const KeyReplacement& replacement = pair.first;
5128 int32_t newKeyCode = pair.second;
5129 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005130 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005131 }
5132 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005133 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005134 }
5135
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005136 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005137 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005138 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005139 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005140 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005141 connection->inputChannel->getFd().get(),
5142 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005143 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005144 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005146 if (!connection->outboundQueue.empty()) {
5147 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5148 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005149 dump += dumpQueue(connection->outboundQueue, currentTime);
5150
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005152 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 }
5154
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005155 if (!connection->waitQueue.empty()) {
5156 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5157 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005158 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005160 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 }
5162 }
5163 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005164 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 }
5166
5167 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005168 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5169 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005171 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 }
5173
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005174 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005175 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5176 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5177 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005178 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005179 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180}
5181
Michael Wright3dd60e22019-03-27 22:06:44 +00005182void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5183 const size_t numMonitors = monitors.size();
5184 for (size_t i = 0; i < numMonitors; i++) {
5185 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005186 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005187 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5188 dump += "\n";
5189 }
5190}
5191
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005192class LooperEventCallback : public LooperCallback {
5193public:
5194 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5195 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5196
5197private:
5198 std::function<int(int events)> mCallback;
5199};
5200
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005201Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005202#if DEBUG_CHANNEL_CREATION
5203 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005204#endif
5205
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005206 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005207 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005208 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005209
5210 if (result) {
5211 return base::Error(result) << "Failed to open input channel pair with name " << name;
5212 }
5213
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005215 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005216 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005217 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005218 sp<Connection> connection =
5219 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005221 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5222 ALOGE("Created a new connection, but the token %p is already known", token.get());
5223 }
5224 mConnectionsByToken.emplace(token, connection);
5225
5226 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5227 this, std::placeholders::_1, token);
5228
5229 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 } // release lock
5231
5232 // Wake the looper because some connections have changed.
5233 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005234 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235}
5236
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005237Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5238 bool isGestureMonitor,
5239 const std::string& name,
5240 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005241 std::shared_ptr<InputChannel> serverChannel;
5242 std::unique_ptr<InputChannel> clientChannel;
5243 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5244 if (result) {
5245 return base::Error(result) << "Failed to open input channel pair with name " << name;
5246 }
5247
Michael Wright3dd60e22019-03-27 22:06:44 +00005248 { // acquire lock
5249 std::scoped_lock _l(mLock);
5250
5251 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005252 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5253 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005254 }
5255
Garfield Tan15601662020-09-22 15:32:38 -07005256 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005257 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005258 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005259
5260 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5261 ALOGE("Created a new connection, but the token %p is already known", token.get());
5262 }
5263 mConnectionsByToken.emplace(token, connection);
5264 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5265 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005267 auto& monitorsByDisplay =
5268 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005269 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005270
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005271 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005272 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5273 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005274 }
Garfield Tan15601662020-09-22 15:32:38 -07005275
Michael Wright3dd60e22019-03-27 22:06:44 +00005276 // Wake the looper because some connections have changed.
5277 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005278 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005279}
5280
Garfield Tan15601662020-09-22 15:32:38 -07005281status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005283 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284
Garfield Tan15601662020-09-22 15:32:38 -07005285 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 if (status) {
5287 return status;
5288 }
5289 } // release lock
5290
5291 // Wake the poll loop because removing the connection may have changed the current
5292 // synchronization state.
5293 mLooper->wake();
5294 return OK;
5295}
5296
Garfield Tan15601662020-09-22 15:32:38 -07005297status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5298 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005299 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005300 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005301 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 return BAD_VALUE;
5303 }
5304
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005305 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005306
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005308 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 }
5310
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005311 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
5313 nsecs_t currentTime = now();
5314 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5315
5316 connection->status = Connection::STATUS_ZOMBIE;
5317 return OK;
5318}
5319
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005320void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5321 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5322 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005323}
5324
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005325void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005326 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005327 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005328 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005329 std::vector<Monitor>& monitors = it->second;
5330 const size_t numMonitors = monitors.size();
5331 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005332 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005333 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5334 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005335 monitors.erase(monitors.begin() + i);
5336 break;
5337 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005338 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005339 if (monitors.empty()) {
5340 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005341 } else {
5342 ++it;
5343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 }
5345}
5346
Michael Wright3dd60e22019-03-27 22:06:44 +00005347status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5348 { // acquire lock
5349 std::scoped_lock _l(mLock);
5350 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5351
5352 if (!foundDisplayId) {
5353 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5354 return BAD_VALUE;
5355 }
5356 int32_t displayId = foundDisplayId.value();
5357
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005358 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5359 mTouchStatesByDisplay.find(displayId);
5360 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005361 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5362 return BAD_VALUE;
5363 }
5364
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005365 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005366 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005367 std::optional<int32_t> foundDeviceId;
5368 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005369 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005370 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005371 foundDeviceId = state.deviceId;
5372 }
5373 }
5374 if (!foundDeviceId || !state.down) {
5375 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005376 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005377 return BAD_VALUE;
5378 }
5379 int32_t deviceId = foundDeviceId.value();
5380
5381 // Send cancel events to all the input channels we're stealing from.
5382 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005383 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005384 options.deviceId = deviceId;
5385 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005386 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005387 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005388 std::shared_ptr<InputChannel> channel =
5389 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005390 if (channel != nullptr) {
5391 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005392 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005393 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005394 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005395 canceledWindows += "]";
5396 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5397 canceledWindows.c_str());
5398
Michael Wright3dd60e22019-03-27 22:06:44 +00005399 // Then clear the current touch state so we stop dispatching to them as well.
5400 state.filterNonMonitors();
5401 }
5402 return OK;
5403}
5404
Prabir Pradhan99987712020-11-10 18:43:05 -08005405void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5406 { // acquire lock
5407 std::scoped_lock _l(mLock);
5408 if (DEBUG_FOCUS) {
5409 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5410 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5411 windowHandle != nullptr ? windowHandle->getName().c_str()
5412 : "token without window");
5413 }
5414
Vishnu Nairc519ff72021-01-21 08:23:08 -08005415 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005416 if (focusedToken != windowToken) {
5417 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5418 enabled ? "enable" : "disable");
5419 return;
5420 }
5421
5422 if (enabled == mFocusedWindowRequestedPointerCapture) {
5423 ALOGW("Ignoring request to %s Pointer Capture: "
5424 "window has %s requested pointer capture.",
5425 enabled ? "enable" : "disable", enabled ? "already" : "not");
5426 return;
5427 }
5428
5429 mFocusedWindowRequestedPointerCapture = enabled;
5430 setPointerCaptureLocked(enabled);
5431 } // release lock
5432
5433 // Wake the thread to process command entries.
5434 mLooper->wake();
5435}
5436
Michael Wright3dd60e22019-03-27 22:06:44 +00005437std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5438 const sp<IBinder>& token) {
5439 for (const auto& it : mGestureMonitorsByDisplay) {
5440 const std::vector<Monitor>& monitors = it.second;
5441 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005442 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005443 return it.first;
5444 }
5445 }
5446 }
5447 return std::nullopt;
5448}
5449
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005450std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5451 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5452 if (gesturePid.has_value()) {
5453 return gesturePid;
5454 }
5455 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5456}
5457
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005458sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005459 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005460 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005461 }
5462
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005463 for (const auto& [token, connection] : mConnectionsByToken) {
5464 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005465 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 }
5467 }
Robert Carr4e670e52018-08-15 13:26:12 -07005468
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005469 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470}
5471
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005472std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5473 sp<Connection> connection = getConnectionLocked(connectionToken);
5474 if (connection == nullptr) {
5475 return "<nullptr>";
5476 }
5477 return connection->getInputChannelName();
5478}
5479
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005480void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005481 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005482 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005483}
5484
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005485void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5486 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005487 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005488 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5489 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 commandEntry->connection = connection;
5491 commandEntry->eventTime = currentTime;
5492 commandEntry->seq = seq;
5493 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005494 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005495 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496}
5497
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005498void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5499 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005501 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005503 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5504 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005506 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507}
5508
Vishnu Nairad321cd2020-08-20 16:40:21 -07005509void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5510 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005511 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5512 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005513 commandEntry->oldToken = oldToken;
5514 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005515 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005516}
5517
arthurhungf452d0b2021-01-06 00:19:52 +08005518void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5519 std::unique_ptr<CommandEntry> commandEntry =
5520 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5521 commandEntry->newToken = token;
5522 commandEntry->x = x;
5523 commandEntry->y = y;
5524 postCommandLocked(std::move(commandEntry));
5525}
5526
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005527void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5528 if (connection == nullptr) {
5529 LOG_ALWAYS_FATAL("Caller must check for nullness");
5530 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005531 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5532 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005533 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005534 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005535 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005536 return;
5537 }
5538 /**
5539 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5540 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5541 * has changed. This could cause newer entries to time out before the already dispatched
5542 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5543 * processes the events linearly. So providing information about the oldest entry seems to be
5544 * most useful.
5545 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005546 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005547 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5548 std::string reason =
5549 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005550 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005551 ns2ms(currentWait),
5552 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005553 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005554 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005555
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005556 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5557
5558 // Stop waking up for events on this connection, it is already unresponsive
5559 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005560}
5561
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005562void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5563 std::string reason =
5564 StringPrintf("%s does not have a focused window", application->getName().c_str());
5565 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005566
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005567 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5568 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5569 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005570 postCommandLocked(std::move(commandEntry));
5571}
5572
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005573void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5574 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5575 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5576 commandEntry->obscuringPackage = obscuringPackage;
5577 postCommandLocked(std::move(commandEntry));
5578}
5579
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005580void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5581 const std::string& reason) {
5582 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5583 updateLastAnrStateLocked(windowLabel, reason);
5584}
5585
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005586void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5587 const std::string& reason) {
5588 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005589 updateLastAnrStateLocked(windowLabel, reason);
5590}
5591
5592void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5593 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005595 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 struct tm tm;
5597 localtime_r(&t, &tm);
5598 char timestr[64];
5599 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005600 mLastAnrState.clear();
5601 mLastAnrState += INDENT "ANR:\n";
5602 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005603 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5604 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005605 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606}
5607
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005608void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 mLock.unlock();
5610
5611 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5612
5613 mLock.lock();
5614}
5615
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005616void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 sp<Connection> connection = commandEntry->connection;
5618
5619 if (connection->status != Connection::STATUS_ZOMBIE) {
5620 mLock.unlock();
5621
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005622 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623
5624 mLock.lock();
5625 }
5626}
5627
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005628void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005629 sp<IBinder> oldToken = commandEntry->oldToken;
5630 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005631 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005632 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005633 mLock.lock();
5634}
5635
arthurhungf452d0b2021-01-06 00:19:52 +08005636void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5637 sp<IBinder> newToken = commandEntry->newToken;
5638 mLock.unlock();
5639 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5640 mLock.lock();
5641}
5642
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005643void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005645
5646 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5647
5648 mLock.lock();
5649}
5650
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005651void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005652 mLock.unlock();
5653
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005654 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655
5656 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005657}
5658
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005659void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005660 mLock.unlock();
5661
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005662 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5663
5664 mLock.lock();
5665}
5666
5667void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5668 mLock.unlock();
5669
5670 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5671
5672 mLock.lock();
5673}
5674
5675void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5676 mLock.unlock();
5677
5678 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005679
5680 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005681}
5682
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005683void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5684 mLock.unlock();
5685
5686 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5687
5688 mLock.lock();
5689}
5690
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5692 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005693 KeyEntry& entry = *(commandEntry->keyEntry);
5694 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695
5696 mLock.unlock();
5697
Michael Wright2b3c3302018-03-02 17:19:13 +00005698 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005699 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005700 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005701 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5702 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005703 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705
5706 mLock.lock();
5707
5708 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005709 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005711 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005713 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5714 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716}
5717
chaviwfd6d3512019-03-25 13:23:49 -07005718void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5719 mLock.unlock();
5720 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5721 mLock.lock();
5722}
5723
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005724/**
5725 * Connection is responsive if it has no events in the waitQueue that are older than the
5726 * current time.
5727 */
5728static bool isConnectionResponsive(const Connection& connection) {
5729 const nsecs_t currentTime = now();
5730 for (const DispatchEntry* entry : connection.waitQueue) {
5731 if (entry->timeoutTime < currentTime) {
5732 return false;
5733 }
5734 }
5735 return true;
5736}
5737
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005738void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005740 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005742 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743
5744 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005745 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005746 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005747 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005749 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005750 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005751 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005752 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5753 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005754 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005755 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5756 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5757 connection->inputChannel->getConnectionToken(),
5758 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5759 finishTime);
5760 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005761
5762 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005763 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005764 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005765 restartEvent =
5766 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005767 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005768 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005769 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5770 handled);
5771 } else {
5772 restartEvent = false;
5773 }
5774
5775 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005776 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005777 // contents of the wait queue to have been drained, so we need to double-check
5778 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005779 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5780 if (dispatchEntryIt != connection->waitQueue.end()) {
5781 dispatchEntry = *dispatchEntryIt;
5782 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005783 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5784 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005785 if (!connection->responsive) {
5786 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005787 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005788 // The connection was unresponsive, and now it's responsive.
5789 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005790 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005791 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005792 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005793 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005794 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005795 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005796 } else {
5797 releaseDispatchEntry(dispatchEntry);
5798 }
5799 }
5800
5801 // Start the next dispatch cycle for this connection.
5802 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803}
5804
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005805void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5806 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5807 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5808 monitorUnresponsiveCommand->pid = pid;
5809 monitorUnresponsiveCommand->reason = std::move(reason);
5810 postCommandLocked(std::move(monitorUnresponsiveCommand));
5811}
5812
5813void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5814 std::string reason) {
5815 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5816 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5817 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5818 windowUnresponsiveCommand->reason = std::move(reason);
5819 postCommandLocked(std::move(windowUnresponsiveCommand));
5820}
5821
5822void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5823 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5824 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5825 monitorResponsiveCommand->pid = pid;
5826 postCommandLocked(std::move(monitorResponsiveCommand));
5827}
5828
5829void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5830 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5831 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5832 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5833 postCommandLocked(std::move(windowResponsiveCommand));
5834}
5835
5836/**
5837 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5838 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5839 * command entry to the command queue.
5840 */
5841void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5842 std::string reason) {
5843 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5844 if (connection.monitor) {
5845 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5846 reason.c_str());
5847 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5848 if (!pid.has_value()) {
5849 ALOGE("Could not find unresponsive monitor for connection %s",
5850 connection.inputChannel->getName().c_str());
5851 return;
5852 }
5853 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5854 return;
5855 }
5856 // If not a monitor, must be a window
5857 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5858 reason.c_str());
5859 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5860}
5861
5862/**
5863 * Tell the policy that a connection has become responsive so that it can stop ANR.
5864 */
5865void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5866 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5867 if (connection.monitor) {
5868 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5869 if (!pid.has_value()) {
5870 ALOGE("Could not find responsive monitor for connection %s",
5871 connection.inputChannel->getName().c_str());
5872 return;
5873 }
5874 sendMonitorResponsiveCommandLocked(pid.value());
5875 return;
5876 }
5877 // If not a monitor, must be a window
5878 sendWindowResponsiveCommandLocked(connectionToken);
5879}
5880
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005882 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005883 KeyEntry& keyEntry, bool handled) {
5884 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005885 if (!handled) {
5886 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005887 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005888 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889 return false;
5890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005892 // Get the fallback key state.
5893 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005894 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005895 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005896 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897 connection->inputState.removeFallbackKey(originalKeyCode);
5898 }
5899
5900 if (handled || !dispatchEntry->hasForegroundTarget()) {
5901 // If the application handles the original key for which we previously
5902 // generated a fallback or if the window is not a foreground window,
5903 // then cancel the associated fallback key, if any.
5904 if (fallbackKeyCode != -1) {
5905 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005907 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005908 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005909 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005911 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913
5914 mLock.unlock();
5915
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005916 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005917 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918
5919 mLock.lock();
5920
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005921 // Cancel the fallback key.
5922 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005924 "application handled the original non-fallback key "
5925 "or is no longer a foreground target, "
5926 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 options.keyCode = fallbackKeyCode;
5928 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005930 connection->inputState.removeFallbackKey(originalKeyCode);
5931 }
5932 } else {
5933 // If the application did not handle a non-fallback key, first check
5934 // that we are in a good state to perform unhandled key event processing
5935 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005936 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005937 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005939 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005940 "since this is not an initial down. "
5941 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005942 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005944 return false;
5945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005947 // Dispatch the unhandled key to the policy.
5948#if DEBUG_OUTBOUND_EVENT_DETAILS
5949 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005950 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005951 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005952#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005953 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005954
5955 mLock.unlock();
5956
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005957 bool fallback =
5958 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005959 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005960
5961 mLock.lock();
5962
5963 if (connection->status != Connection::STATUS_NORMAL) {
5964 connection->inputState.removeFallbackKey(originalKeyCode);
5965 return false;
5966 }
5967
5968 // Latch the fallback keycode for this key on an initial down.
5969 // The fallback keycode cannot change at any other point in the lifecycle.
5970 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005972 fallbackKeyCode = event.getKeyCode();
5973 } else {
5974 fallbackKeyCode = AKEYCODE_UNKNOWN;
5975 }
5976 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5977 }
5978
5979 ALOG_ASSERT(fallbackKeyCode != -1);
5980
5981 // Cancel the fallback key if the policy decides not to send it anymore.
5982 // We will continue to dispatch the key to the policy but we will no
5983 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005984 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5985 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005986#if DEBUG_OUTBOUND_EVENT_DETAILS
5987 if (fallback) {
5988 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005989 "as a fallback for %d, but on the DOWN it had requested "
5990 "to send %d instead. Fallback canceled.",
5991 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005992 } else {
5993 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005994 "but on the DOWN it had requested to send %d. "
5995 "Fallback canceled.",
5996 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005997 }
5998#endif
5999
6000 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6001 "canceling fallback, policy no longer desires it");
6002 options.keyCode = fallbackKeyCode;
6003 synthesizeCancelationEventsForConnectionLocked(connection, options);
6004
6005 fallback = false;
6006 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006007 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006008 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006009 }
6010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011
6012#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006013 {
6014 std::string msg;
6015 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6016 connection->inputState.getFallbackKeys();
6017 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006018 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006019 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006020 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006021 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006022 }
6023#endif
6024
6025 if (fallback) {
6026 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006027 keyEntry.eventTime = event.getEventTime();
6028 keyEntry.deviceId = event.getDeviceId();
6029 keyEntry.source = event.getSource();
6030 keyEntry.displayId = event.getDisplayId();
6031 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6032 keyEntry.keyCode = fallbackKeyCode;
6033 keyEntry.scanCode = event.getScanCode();
6034 keyEntry.metaState = event.getMetaState();
6035 keyEntry.repeatCount = event.getRepeatCount();
6036 keyEntry.downTime = event.getDownTime();
6037 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006038
6039#if DEBUG_OUTBOUND_EVENT_DETAILS
6040 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006041 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006042 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043#endif
6044 return true; // restart the event
6045 } else {
6046#if DEBUG_OUTBOUND_EVENT_DETAILS
6047 ALOGD("Unhandled key event: No fallback key.");
6048#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006049
6050 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006051 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 }
6053 }
6054 return false;
6055}
6056
6057bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006058 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006059 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 return false;
6061}
6062
6063void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6064 mLock.unlock();
6065
Sean Stoutb4e0a592021-02-23 07:34:53 -08006066 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6067 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068
6069 mLock.lock();
6070}
6071
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072void InputDispatcher::traceInboundQueueLengthLocked() {
6073 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006074 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 }
6076}
6077
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006078void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 if (ATRACE_ENABLED()) {
6080 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006081 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6082 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 }
6084}
6085
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006086void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 if (ATRACE_ENABLED()) {
6088 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006089 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6090 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 }
6092}
6093
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006094void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006095 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006097 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098 dumpDispatchStateLocked(dump);
6099
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006100 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006101 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006102 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103 }
6104}
6105
6106void InputDispatcher::monitor() {
6107 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006108 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006109 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006110 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111}
6112
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006113/**
6114 * Wake up the dispatcher and wait until it processes all events and commands.
6115 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6116 * this method can be safely called from any thread, as long as you've ensured that
6117 * the work you are interested in completing has already been queued.
6118 */
6119bool InputDispatcher::waitForIdle() {
6120 /**
6121 * Timeout should represent the longest possible time that a device might spend processing
6122 * events and commands.
6123 */
6124 constexpr std::chrono::duration TIMEOUT = 100ms;
6125 std::unique_lock lock(mLock);
6126 mLooper->wake();
6127 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6128 return result == std::cv_status::no_timeout;
6129}
6130
Vishnu Naire798b472020-07-23 13:52:21 -07006131/**
6132 * Sets focus to the window identified by the token. This must be called
6133 * after updating any input window handles.
6134 *
6135 * Params:
6136 * request.token - input channel token used to identify the window that should gain focus.
6137 * request.focusedToken - the token that the caller expects currently to be focused. If the
6138 * specified token does not match the currently focused window, this request will be dropped.
6139 * If the specified focused token matches the currently focused window, the call will succeed.
6140 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6141 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6142 * when requesting the focus change. This determines which request gets
6143 * precedence if there is a focus change request from another source such as pointer down.
6144 */
Vishnu Nair958da932020-08-21 17:12:37 -07006145void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6146 { // acquire lock
6147 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006148 std::optional<FocusResolver::FocusChanges> changes =
6149 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6150 if (changes) {
6151 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006152 }
6153 } // release lock
6154 // Wake up poll loop since it may need to make new input dispatching choices.
6155 mLooper->wake();
6156}
6157
Vishnu Nairc519ff72021-01-21 08:23:08 -08006158void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6159 if (changes.oldFocus) {
6160 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006161 if (focusedInputChannel) {
6162 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6163 "focus left window");
6164 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006165 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006166 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006167 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006168 if (changes.newFocus) {
6169 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006170 }
6171
Prabir Pradhan99987712020-11-10 18:43:05 -08006172 // If a window has pointer capture, then it must have focus. We need to ensure that this
6173 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6174 // If the window loses focus before it loses pointer capture, then the window can be in a state
6175 // where it has pointer capture but not focus, violating the contract. Therefore we must
6176 // dispatch the pointer capture event before the focus event. Since focus events are added to
6177 // the front of the queue (above), we add the pointer capture event to the front of the queue
6178 // after the focus events are added. This ensures the pointer capture event ends up at the
6179 // front.
6180 disablePointerCaptureForcedLocked();
6181
Vishnu Nairc519ff72021-01-21 08:23:08 -08006182 if (mFocusedDisplayId == changes.displayId) {
6183 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006184 }
6185}
Vishnu Nair958da932020-08-21 17:12:37 -07006186
Prabir Pradhan99987712020-11-10 18:43:05 -08006187void InputDispatcher::disablePointerCaptureForcedLocked() {
6188 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6189 return;
6190 }
6191
6192 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6193
6194 if (mFocusedWindowRequestedPointerCapture) {
6195 mFocusedWindowRequestedPointerCapture = false;
6196 setPointerCaptureLocked(false);
6197 }
6198
6199 if (!mWindowTokenWithPointerCapture) {
6200 // No need to send capture changes because no window has capture.
6201 return;
6202 }
6203
6204 if (mPendingEvent != nullptr) {
6205 // Move the pending event to the front of the queue. This will give the chance
6206 // for the pending event to be dropped if it is a captured event.
6207 mInboundQueue.push_front(mPendingEvent);
6208 mPendingEvent = nullptr;
6209 }
6210
6211 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6212 false /* hasCapture */);
6213 mInboundQueue.push_front(std::move(entry));
6214}
6215
Prabir Pradhan99987712020-11-10 18:43:05 -08006216void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6217 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6218 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6219 commandEntry->enabled = enabled;
6220 postCommandLocked(std::move(commandEntry));
6221}
6222
6223void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6224 android::inputdispatcher::CommandEntry* commandEntry) {
6225 mLock.unlock();
6226
6227 mPolicy->setPointerCapture(commandEntry->enabled);
6228
6229 mLock.lock();
6230}
6231
Vishnu Nair599f1412021-06-21 10:39:58 -07006232void InputDispatcher::displayRemoved(int32_t displayId) {
6233 { // acquire lock
6234 std::scoped_lock _l(mLock);
6235 // Set an empty list to remove all handles from the specific display.
6236 setInputWindowsLocked(/* window handles */ {}, displayId);
6237 setFocusedApplicationLocked(displayId, nullptr);
6238 // Call focus resolver to clean up stale requests. This must be called after input windows
6239 // have been removed for the removed display.
6240 mFocusResolver.displayRemoved(displayId);
6241 } // release lock
6242
6243 // Wake up poll loop since it may need to make new input dispatching choices.
6244 mLooper->wake();
6245}
6246
Garfield Tane84e6f92019-08-29 17:28:41 -07006247} // namespace android::inputdispatcher