blob: ce1f266cfbecf8b0e0401d7d8a0abafd4e0dd8cf [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080052#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050053#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070054#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100055#include <binder/IServiceManager.h>
56#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080057#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080081using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000082using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080083using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100085using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080086using android::os::InputEventInjectionResult;
87using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100088using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080089
Garfield Tane84e6f92019-08-29 17:28:41 -070090namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Prabir Pradhan93a0f912021-04-21 13:47:42 -070092// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
93// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
94static bool isPerWindowInputRotationEnabled() {
95 static const bool PER_WINDOW_INPUT_ROTATION =
96 base::GetBoolProperty("persist.debug.per_window_input_rotation", false);
97 return PER_WINDOW_INPUT_ROTATION;
98}
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100// Default input dispatching timeout if there is no focused application or paused window
101// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800102const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
103 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
104 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105
106// Amount of time to allow for all pending events to be processed when an app switch
107// key is on the way. This is used to preempt input dispatch and drop input events
108// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
111// Amount of time to allow for an event to be dispatched (measured since its eventTime)
112// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000113constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
117
118// Log a warning when an interception call takes longer than this to process.
119constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700121// Additional key latency in case a connection is still processing some motion events.
122// This will help with the case when a user touched a button that opens a new window,
123// and gives us the chance to dispatch the key to this new window.
124constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000127constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
128
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000129// Event log tags. See EventLogTags.logtags for reference
130constexpr int LOGTAG_INPUT_INTERACTION = 62000;
131constexpr int LOGTAG_INPUT_FOCUS = 62001;
132
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133static inline nsecs_t now() {
134 return systemTime(SYSTEM_TIME_MONOTONIC);
135}
136
137static inline const char* toString(bool value) {
138 return value ? "true" : "false";
139}
140
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000141static inline const std::string toString(sp<IBinder> binder) {
142 if (binder == nullptr) {
143 return "<null>";
144 }
145 return StringPrintf("%p", binder.get());
146}
147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
150 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151}
152
153static bool isValidKeyAction(int32_t action) {
154 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AKEY_EVENT_ACTION_DOWN:
156 case AKEY_EVENT_ACTION_UP:
157 return true;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
163static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 ALOGE("Key event has invalid action code 0x%x", action);
166 return false;
167 }
168 return true;
169}
170
Michael Wright7b159c92015-05-14 14:48:03 +0100171static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_DOWN:
174 case AMOTION_EVENT_ACTION_UP:
175 case AMOTION_EVENT_ACTION_CANCEL:
176 case AMOTION_EVENT_ACTION_MOVE:
177 case AMOTION_EVENT_ACTION_OUTSIDE:
178 case AMOTION_EVENT_ACTION_HOVER_ENTER:
179 case AMOTION_EVENT_ACTION_HOVER_MOVE:
180 case AMOTION_EVENT_ACTION_HOVER_EXIT:
181 case AMOTION_EVENT_ACTION_SCROLL:
182 return true;
183 case AMOTION_EVENT_ACTION_POINTER_DOWN:
184 case AMOTION_EVENT_ACTION_POINTER_UP: {
185 int32_t index = getMotionEventActionPointerIndex(action);
186 return index >= 0 && index < pointerCount;
187 }
188 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
189 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
190 return actionButton != 0;
191 default:
192 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 }
194}
195
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500196static int64_t millis(std::chrono::nanoseconds t) {
197 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
198}
199
Michael Wright7b159c92015-05-14 14:48:03 +0100200static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700201 const PointerProperties* pointerProperties) {
202 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 ALOGE("Motion event has invalid action code 0x%x", action);
204 return false;
205 }
206 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000207 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700208 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 return false;
210 }
211 BitSet32 pointerIdBits;
212 for (size_t i = 0; i < pointerCount; i++) {
213 int32_t id = pointerProperties[i].id;
214 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700215 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
216 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 return false;
218 }
219 if (pointerIdBits.hasBit(id)) {
220 ALOGE("Motion event has duplicate pointer id %d", id);
221 return false;
222 }
223 pointerIdBits.markBit(id);
224 }
225 return true;
226}
227
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000230 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
232
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000233 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 bool first = true;
235 Region::const_iterator cur = region.begin();
236 Region::const_iterator const tail = region.end();
237 while (cur != tail) {
238 if (first) {
239 first = false;
240 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800241 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800243 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 cur++;
245 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000246 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247}
248
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500249static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
250 constexpr size_t maxEntries = 50; // max events to print
251 constexpr size_t skipBegin = maxEntries / 2;
252 const size_t skipEnd = queue.size() - maxEntries / 2;
253 // skip from maxEntries / 2 ... size() - maxEntries/2
254 // only print from 0 .. skipBegin and then from skipEnd .. size()
255
256 std::string dump;
257 for (size_t i = 0; i < queue.size(); i++) {
258 const DispatchEntry& entry = *queue[i];
259 if (i >= skipBegin && i < skipEnd) {
260 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
261 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
262 continue;
263 }
264 dump.append(INDENT4);
265 dump += entry.eventEntry->getDescription();
266 dump += StringPrintf(", seq=%" PRIu32
267 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
268 entry.seq, entry.targetFlags, entry.resolvedAction,
269 ns2ms(currentTime - entry.eventEntry->eventTime));
270 if (entry.deliveryTime != 0) {
271 // This entry was delivered, so add information on how long we've been waiting
272 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
273 }
274 dump.append("\n");
275 }
276 return dump;
277}
278
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700279/**
280 * Find the entry in std::unordered_map by key, and return it.
281 * If the entry is not found, return a default constructed entry.
282 *
283 * Useful when the entries are vectors, since an empty vector will be returned
284 * if the entry is not found.
285 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
286 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700287template <typename K, typename V>
288static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700289 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700290 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800291}
292
chaviwaf87b3e2019-10-01 16:59:28 -0700293static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
294 if (first == second) {
295 return true;
296 }
297
298 if (first == nullptr || second == nullptr) {
299 return false;
300 }
301
302 return first->getToken() == second->getToken();
303}
304
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000305static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
306 if (first == nullptr || second == nullptr) {
307 return false;
308 }
309 return first->applicationInfo.token != nullptr &&
310 first->applicationInfo.token == second->applicationInfo.token;
311}
312
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800313static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
314 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
315}
316
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700318 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900320 if (eventEntry->type == EventEntry::Type::MOTION) {
321 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800322 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900323 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800324 // Use identity transform for events that are not pointer events because their axes
325 // values do not represent on-screen coordinates, so they should not have any window
326 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900327 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700328 1.0f /*globalScaleFactor*/,
329 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900330 }
331 }
332
chaviw1ff3d1e2020-07-01 15:53:47 -0700333 if (inputTarget.useDefaultPointerTransform()) {
334 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700335 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700336 inputTarget.globalScaleFactor,
337 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 }
339
340 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
341 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700343 std::vector<PointerCoords> pointerCoords;
344 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 // Use the first pointer information to normalize all other pointers. This could be any pointer
347 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700348 // uses the transform for the normalized pointer.
349 const ui::Transform& firstPointerTransform =
350 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
351 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352
353 // Iterate through all pointers in the event to normalize against the first.
354 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
355 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
356 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358
359 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700360 // First, apply the current pointer's transform to update the coordinates into
361 // window space.
362 pointerCoords[pointerIndex].transform(currTransform);
363 // Next, apply the inverse transform of the normalized coordinates so the
364 // current coordinates are transformed into the normalized coordinate space.
365 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366 }
367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700368 std::unique_ptr<MotionEntry> combinedMotionEntry =
369 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
370 motionEntry.deviceId, motionEntry.source,
371 motionEntry.displayId, motionEntry.policyFlags,
372 motionEntry.action, motionEntry.actionButton,
373 motionEntry.flags, motionEntry.metaState,
374 motionEntry.buttonState, motionEntry.classification,
375 motionEntry.edgeFlags, motionEntry.xPrecision,
376 motionEntry.yPrecision, motionEntry.xCursorPosition,
377 motionEntry.yCursorPosition, motionEntry.downTime,
378 motionEntry.pointerCount, motionEntry.pointerProperties,
379 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 if (motionEntry.injectionState) {
382 combinedMotionEntry->injectionState = motionEntry.injectionState;
383 combinedMotionEntry->injectionState->refCount += 1;
384 }
385
386 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700387 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700388 firstPointerTransform, inputTarget.globalScaleFactor,
389 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 return dispatchEntry;
391}
392
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700393static void addGestureMonitors(const std::vector<Monitor>& monitors,
394 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
395 float yOffset = 0) {
396 if (monitors.empty()) {
397 return;
398 }
399 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
400 for (const Monitor& monitor : monitors) {
401 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
402 }
403}
404
Garfield Tan15601662020-09-22 15:32:38 -0700405static status_t openInputChannelPair(const std::string& name,
406 std::shared_ptr<InputChannel>& serverChannel,
407 std::unique_ptr<InputChannel>& clientChannel) {
408 std::unique_ptr<InputChannel> uniqueServerChannel;
409 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
410
411 serverChannel = std::move(uniqueServerChannel);
412 return result;
413}
414
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500415template <typename T>
416static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
417 if (lhs == nullptr && rhs == nullptr) {
418 return true;
419 }
420 if (lhs == nullptr || rhs == nullptr) {
421 return false;
422 }
423 return *lhs == *rhs;
424}
425
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000426static sp<IPlatformCompatNative> getCompatService() {
427 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
428 if (service == nullptr) {
429 ALOGE("Failed to link to compat service");
430 return nullptr;
431 }
432 return interface_cast<IPlatformCompatNative>(service);
433}
434
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000435static KeyEvent createKeyEvent(const KeyEntry& entry) {
436 KeyEvent event;
437 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
438 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
439 entry.repeatCount, entry.downTime, entry.eventTime);
440 return event;
441}
442
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000443static std::optional<int32_t> findMonitorPidByToken(
444 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
445 const sp<IBinder>& token) {
446 for (const auto& it : monitorsByDisplay) {
447 const std::vector<Monitor>& monitors = it.second;
448 for (const Monitor& monitor : monitors) {
449 if (monitor.inputChannel->getConnectionToken() == token) {
450 return monitor.pid;
451 }
452 }
453 }
454 return std::nullopt;
455}
456
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000457static bool shouldReportMetricsForConnection(const Connection& connection) {
458 // Do not keep track of gesture monitors. They receive every event and would disproportionately
459 // affect the statistics.
460 if (connection.monitor) {
461 return false;
462 }
463 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
464 if (!connection.responsive) {
465 return false;
466 }
467 return true;
468}
469
470static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
471 const Connection& connection) {
472 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
473 const int32_t& inputEventId = eventEntry.id;
474 if (inputEventId != dispatchEntry.resolvedEventId) {
475 // Event was transmuted
476 return false;
477 }
478 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
479 return false;
480 }
481 // Only track latency for events that originated from hardware
482 if (eventEntry.isSynthesized()) {
483 return false;
484 }
485 const EventEntry::Type& inputEventEntryType = eventEntry.type;
486 if (inputEventEntryType == EventEntry::Type::KEY) {
487 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
488 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
489 return false;
490 }
491 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
492 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
493 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
494 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
495 return false;
496 }
497 } else {
498 // Not a key or a motion
499 return false;
500 }
501 if (!shouldReportMetricsForConnection(connection)) {
502 return false;
503 }
504 return true;
505}
506
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507// --- InputDispatcher ---
508
Garfield Tan00f511d2019-06-12 16:55:40 -0700509InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
510 : mPolicy(policy),
511 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700512 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800513 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700514 mAppSwitchSawKeyDown(false),
515 mAppSwitchDueTime(LONG_LONG_MAX),
516 mNextUnblockedEvent(nullptr),
517 mDispatchEnabled(false),
518 mDispatchFrozen(false),
519 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800520 // mInTouchMode will be initialized by the WindowManager to the default device config.
521 // To avoid leaking stack in case that call never comes, and for tests,
522 // initialize it here anyways.
523 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100524 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000525 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800526 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000527 mLatencyAggregator(),
528 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000529 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800531 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532
Yi Kong9b14ac62018-07-17 13:48:38 -0700533 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 policy->getDispatcherConfiguration(&mConfig);
536}
537
538InputDispatcher::~InputDispatcher() {
539 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800540 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541
542 resetKeyRepeatLocked();
543 releasePendingEventLocked();
544 drainInboundQueueLocked();
545 }
546
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000547 while (!mConnectionsByToken.empty()) {
548 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700549 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 }
551}
552
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700553status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700554 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700555 return ALREADY_EXISTS;
556 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700557 mThread = std::make_unique<InputThread>(
558 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
559 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700560}
561
562status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700563 if (mThread && mThread->isCallingThread()) {
564 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700565 return INVALID_OPERATION;
566 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700567 mThread.reset();
568 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700569}
570
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571void InputDispatcher::dispatchOnce() {
572 nsecs_t nextWakeupTime = LONG_LONG_MAX;
573 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800574 std::scoped_lock _l(mLock);
575 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
577 // Run a dispatch loop if there are no pending commands.
578 // The dispatch loop might enqueue commands to run afterwards.
579 if (!haveCommandsLocked()) {
580 dispatchOnceInnerLocked(&nextWakeupTime);
581 }
582
583 // Run all pending commands if there are any.
584 // If any commands were run then force the next poll to wake up immediately.
585 if (runCommandsLockedInterruptible()) {
586 nextWakeupTime = LONG_LONG_MIN;
587 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800588
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700589 // If we are still waiting for ack on some events,
590 // we might have to wake up earlier to check if an app is anr'ing.
591 const nsecs_t nextAnrCheck = processAnrsLocked();
592 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
593
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800594 // We are about to enter an infinitely long sleep, because we have no commands or
595 // pending or queued events
596 if (nextWakeupTime == LONG_LONG_MAX) {
597 mDispatcherEnteredIdle.notify_all();
598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 } // release lock
600
601 // Wait for callback or timeout or wake. (make sure we round up, not down)
602 nsecs_t currentTime = now();
603 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
604 mLooper->pollOnce(timeoutMillis);
605}
606
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700607/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500608 * Raise ANR if there is no focused window.
609 * Before the ANR is raised, do a final state check:
610 * 1. The currently focused application must be the same one we are waiting for.
611 * 2. Ensure we still don't have a focused window.
612 */
613void InputDispatcher::processNoFocusedWindowAnrLocked() {
614 // Check if the application that we are waiting for is still focused.
615 std::shared_ptr<InputApplicationHandle> focusedApplication =
616 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
617 if (focusedApplication == nullptr ||
618 focusedApplication->getApplicationToken() !=
619 mAwaitedFocusedApplication->getApplicationToken()) {
620 // Unexpected because we should have reset the ANR timer when focused application changed
621 ALOGE("Waited for a focused window, but focused application has already changed to %s",
622 focusedApplication->getName().c_str());
623 return; // The focused application has changed.
624 }
625
626 const sp<InputWindowHandle>& focusedWindowHandle =
627 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
628 if (focusedWindowHandle != nullptr) {
629 return; // We now have a focused window. No need for ANR.
630 }
631 onAnrLocked(mAwaitedFocusedApplication);
632}
633
634/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700635 * Check if any of the connections' wait queues have events that are too old.
636 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
637 * Return the time at which we should wake up next.
638 */
639nsecs_t InputDispatcher::processAnrsLocked() {
640 const nsecs_t currentTime = now();
641 nsecs_t nextAnrCheck = LONG_LONG_MAX;
642 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
643 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
644 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500645 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700646 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500647 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700648 return LONG_LONG_MIN;
649 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500650 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700651 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
652 }
653 }
654
655 // Check if any connection ANRs are due
656 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
657 if (currentTime < nextAnrCheck) { // most likely scenario
658 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
659 }
660
661 // If we reached here, we have an unresponsive connection.
662 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
663 if (connection == nullptr) {
664 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
665 return nextAnrCheck;
666 }
667 connection->responsive = false;
668 // Stop waking up for this unresponsive connection
669 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000670 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671 return LONG_LONG_MIN;
672}
673
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500674std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700675 sp<InputWindowHandle> window = getWindowHandleLocked(token);
676 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500677 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500679 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700680}
681
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
683 nsecs_t currentTime = now();
684
Jeff Browndc5992e2014-04-11 01:27:26 -0700685 // Reset the key repeat timer whenever normal dispatch is suspended while the
686 // device is in a non-interactive state. This is to ensure that we abort a key
687 // repeat if the device is just coming out of sleep.
688 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 resetKeyRepeatLocked();
690 }
691
692 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
693 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100694 if (DEBUG_FOCUS) {
695 ALOGD("Dispatch frozen. Waiting some more.");
696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 return;
698 }
699
700 // Optimize latency of app switches.
701 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
702 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
703 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
704 if (mAppSwitchDueTime < *nextWakeupTime) {
705 *nextWakeupTime = mAppSwitchDueTime;
706 }
707
708 // Ready to start a new event.
709 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700711 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 if (isAppSwitchDue) {
713 // The inbound queue is empty so the app switch key we were waiting
714 // for will never arrive. Stop waiting for it.
715 resetPendingAppSwitchLocked(false);
716 isAppSwitchDue = false;
717 }
718
719 // Synthesize a key repeat if appropriate.
720 if (mKeyRepeatState.lastKeyEntry) {
721 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
722 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
723 } else {
724 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
725 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
726 }
727 }
728 }
729
730 // Nothing to do if there is no pending event.
731 if (!mPendingEvent) {
732 return;
733 }
734 } else {
735 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700736 mPendingEvent = mInboundQueue.front();
737 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 traceInboundQueueLengthLocked();
739 }
740
741 // Poke user activity for this event.
742 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700743 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 }
746
747 // Now we have an event to dispatch.
748 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700749 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700751 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700753 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700755 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757
758 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700759 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 }
761
762 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700763 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700764 const ConfigurationChangedEntry& typedEntry =
765 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 break;
769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700771 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700772 const DeviceResetEntry& typedEntry =
773 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700775 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700776 break;
777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100779 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700780 std::shared_ptr<FocusEntry> typedEntry =
781 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100782 dispatchFocusLocked(currentTime, typedEntry);
783 done = true;
784 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
785 break;
786 }
787
Prabir Pradhan99987712020-11-10 18:43:05 -0800788 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
789 const auto typedEntry =
790 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
791 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
792 done = true;
793 break;
794 }
795
arthurhungb89ccb02020-12-30 16:19:01 +0800796 case EventEntry::Type::DRAG: {
797 std::shared_ptr<DragEntry> typedEntry =
798 std::static_pointer_cast<DragEntry>(mPendingEvent);
799 dispatchDragLocked(currentTime, typedEntry);
800 done = true;
801 break;
802 }
803
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700804 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700805 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 resetPendingAppSwitchLocked(true);
809 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 } else if (dropReason == DropReason::NOT_DROPPED) {
811 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 }
813 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700814 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700815 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700817 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
818 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700821 break;
822 }
823
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700824 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700825 std::shared_ptr<MotionEntry> motionEntry =
826 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700827 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
828 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700830 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700831 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700833 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
834 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700836 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700837 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
Chris Yef59a2f42020-10-16 12:55:26 -0700839
840 case EventEntry::Type::SENSOR: {
841 std::shared_ptr<SensorEntry> sensorEntry =
842 std::static_pointer_cast<SensorEntry>(mPendingEvent);
843 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
844 dropReason = DropReason::APP_SWITCH;
845 }
846 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
847 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
848 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
849 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
850 dropReason = DropReason::STALE;
851 }
852 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
853 done = true;
854 break;
855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 }
857
858 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700860 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 }
Michael Wright3a981722015-06-10 15:26:13 +0100862 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863
864 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 }
867}
868
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700869/**
870 * Return true if the events preceding this incoming motion event should be dropped
871 * Return false otherwise (the default behaviour)
872 */
873bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700874 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700875 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700876
877 // Optimize case where the current application is unresponsive and the user
878 // decides to touch a window in a different application.
879 // If the application takes too long to catch up then we drop all events preceding
880 // the touch into the other window.
881 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700882 int32_t displayId = motionEntry.displayId;
883 int32_t x = static_cast<int32_t>(
884 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
885 int32_t y = static_cast<int32_t>(
886 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
887 sp<InputWindowHandle> touchedWindowHandle =
888 findTouchedWindowAtLocked(displayId, x, y, nullptr);
889 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890 touchedWindowHandle->getApplicationToken() !=
891 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700892 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 ALOGI("Pruning input queue because user touched a different application while waiting "
894 "for %s",
895 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700896 return true;
897 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898
899 // Alternatively, maybe there's a gesture monitor that could handle this event
900 std::vector<TouchedMonitor> gestureMonitors =
901 findTouchedGestureMonitorsLocked(displayId, {});
902 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
903 sp<Connection> connection =
904 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000905 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700906 // This monitor could take more input. Drop all events preceding this
907 // event, so that gesture monitor could get a chance to receive the stream
908 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
909 "responsive gesture monitor that may handle the event",
910 mAwaitedFocusedApplication->getName().c_str());
911 return true;
912 }
913 }
914 }
915
916 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
917 // yet been processed by some connections, the dispatcher will wait for these motion
918 // events to be processed before dispatching the key event. This is because these motion events
919 // may cause a new window to be launched, which the user might expect to receive focus.
920 // To prevent waiting forever for such events, just send the key to the currently focused window
921 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
922 ALOGD("Received a new pointer down event, stop waiting for events to process and "
923 "just send the pending key event to the focused window.");
924 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700925 }
926 return false;
927}
928
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700929bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700930 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700931 mInboundQueue.push_back(std::move(newEntry));
932 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 traceInboundQueueLengthLocked();
934
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700935 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700936 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 // Optimize app switch latency.
938 // If the application takes too long to catch up then we drop all events preceding
939 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700940 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700942 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700944 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700949 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 mAppSwitchSawKeyDown = false;
951 needWake = true;
952 }
953 }
954 }
955 break;
956 }
957
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700958 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700959 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
960 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100965 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700966 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
967 break;
968 }
969 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800970 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700971 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800972 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
973 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700974 // nothing to do
975 break;
976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 }
978
979 return needWake;
980}
981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700983 // Do not store sensor event in recent queue to avoid flooding the queue.
984 if (entry->type != EventEntry::Type::SENSOR) {
985 mRecentQueue.push_back(entry);
986 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700987 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700988 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
990}
991
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700993 int32_t y, TouchState* touchState,
994 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800995 bool addPortalWindows,
996 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700997 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
998 LOG_ALWAYS_FATAL(
999 "Must provide a valid touch state if adding portal windows or outside targets");
1000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -07001002 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001003 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001004 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001005 continue;
1006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1008 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001009 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010
1011 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001012 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1013 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1014 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001016 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1018 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001019 if (addPortalWindows) {
1020 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001021 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001022 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001023 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 // Found window.
1027 return windowHandle;
1028 }
1029 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001030
Michael Wright44753b12020-07-08 13:48:11 +01001031 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001032 touchState->addOrUpdateWindow(windowHandle,
1033 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1034 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
1038 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001039 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040}
1041
Garfield Tane84e6f92019-08-29 17:28:41 -07001042std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001043 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001044 std::vector<TouchedMonitor> touchedMonitors;
1045
1046 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1047 addGestureMonitors(monitors, touchedMonitors);
1048 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1049 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1050 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1052 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001053 }
1054 return touchedMonitors;
1055}
1056
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001057void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 const char* reason;
1059 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001060 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 reason = "inbound event was dropped because the policy consumed it";
1065 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 case DropReason::DISABLED:
1067 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 ALOGI("Dropped event because input dispatch is disabled.");
1069 }
1070 reason = "inbound event was dropped because input dispatch is disabled";
1071 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 ALOGI("Dropped event because of pending overdue app switch.");
1074 reason = "inbound event was dropped because of pending overdue app switch";
1075 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 ALOGI("Dropped event because the current application is not responding and the user "
1078 "has started interacting with a different application.");
1079 reason = "inbound event was dropped because the current application is not responding "
1080 "and the user has started interacting with a different application";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 ALOGI("Dropped event because it is stale.");
1084 reason = "inbound event was dropped because it is stale";
1085 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001086 case DropReason::NO_POINTER_CAPTURE:
1087 ALOGI("Dropped event because there is no window with Pointer Capture.");
1088 reason = "inbound event was dropped because there is no window with Pointer Capture";
1089 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001090 case DropReason::NOT_DROPPED: {
1091 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001096 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001097 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1099 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001102 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001103 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1104 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1106 synthesizeCancelationEventsForAllConnectionsLocked(options);
1107 } else {
1108 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1109 synthesizeCancelationEventsForAllConnectionsLocked(options);
1110 }
1111 break;
1112 }
Chris Yef59a2f42020-10-16 12:55:26 -07001113 case EventEntry::Type::SENSOR: {
1114 break;
1115 }
arthurhungb89ccb02020-12-30 16:19:01 +08001116 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1117 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001118 break;
1119 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001120 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001121 case EventEntry::Type::CONFIGURATION_CHANGED:
1122 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001123 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 break;
1125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 }
1127}
1128
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001129static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1131 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132}
1133
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001134bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1135 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1136 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1137 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138}
1139
1140bool InputDispatcher::isAppSwitchPendingLocked() {
1141 return mAppSwitchDueTime != LONG_LONG_MAX;
1142}
1143
1144void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1145 mAppSwitchDueTime = LONG_LONG_MAX;
1146
1147#if DEBUG_APP_SWITCH
1148 if (handled) {
1149 ALOGD("App switch has arrived.");
1150 } else {
1151 ALOGD("App switch was abandoned.");
1152 }
1153#endif
1154}
1155
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001157 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158}
1159
1160bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001161 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 return false;
1163 }
1164
1165 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001166 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001167 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001169 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170
1171 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001172 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 return true;
1174}
1175
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001176void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1177 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178}
1179
1180void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001181 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001182 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001183 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 releaseInboundEventLocked(entry);
1185 }
1186 traceInboundQueueLengthLocked();
1187}
1188
1189void InputDispatcher::releasePendingEventLocked() {
1190 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001192 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194}
1195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001198 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199#if DEBUG_DISPATCH_CYCLE
1200 ALOGD("Injected inbound event was dropped.");
1201#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001205 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208}
1209
1210void InputDispatcher::resetKeyRepeatLocked() {
1211 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001212 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214}
1215
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001216std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1217 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218
Michael Wright2e732952014-09-24 13:26:59 -07001219 uint32_t policyFlags = entry->policyFlags &
1220 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 std::shared_ptr<KeyEntry> newEntry =
1223 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1224 entry->source, entry->displayId, policyFlags, entry->action,
1225 entry->flags, entry->keyCode, entry->scanCode,
1226 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 newEntry->syntheticRepeat = true;
1229 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232}
1233
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001234bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238#endif
1239
1240 // Reset key repeating in case a keyboard device was added or removed or something.
1241 resetKeyRepeatLocked();
1242
1243 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001244 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1245 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001247 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 return true;
1249}
1250
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1252 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1255 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256#endif
1257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001259 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 synthesizeCancelationEventsForAllConnectionsLocked(options);
1261 return true;
1262}
1263
Vishnu Nairad321cd2020-08-20 16:40:21 -07001264void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001265 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001266 if (mPendingEvent != nullptr) {
1267 // Move the pending event to the front of the queue. This will give the chance
1268 // for the pending event to get dispatched to the newly focused window
1269 mInboundQueue.push_front(mPendingEvent);
1270 mPendingEvent = nullptr;
1271 }
1272
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 std::unique_ptr<FocusEntry> focusEntry =
1274 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1275 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001276
1277 // This event should go to the front of the queue, but behind all other focus events
1278 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001280 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 [](const std::shared_ptr<EventEntry>& event) {
1282 return event->type == EventEntry::Type::FOCUS;
1283 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001284
1285 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001287}
1288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001290 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001291 if (channel == nullptr) {
1292 return; // Window has gone away
1293 }
1294 InputTarget target;
1295 target.inputChannel = channel;
1296 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1297 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001298 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1299 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001300 std::string reason = std::string("reason=").append(entry->reason);
1301 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001302 dispatchEventLocked(currentTime, entry, {target});
1303}
1304
Prabir Pradhan99987712020-11-10 18:43:05 -08001305void InputDispatcher::dispatchPointerCaptureChangedLocked(
1306 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1307 DropReason& dropReason) {
Prabir Pradhanf192a102021-08-06 14:01:18 +00001308 dropReason = DropReason::NOT_DROPPED;
1309
Prabir Pradhan99987712020-11-10 18:43:05 -08001310 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001311 sp<IBinder> token;
Prabir Pradhanf192a102021-08-06 14:01:18 +00001312
1313 if (entry->pointerCaptureRequest.enable) {
1314 // Enable Pointer Capture.
1315 if (haveWindowWithPointerCapture &&
1316 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1317 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1318 "to the window.");
1319 }
1320 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001321 // This can happen if a window requests capture and immediately releases capture.
1322 ALOGW("No window requested Pointer Capture.");
Prabir Pradhanf192a102021-08-06 14:01:18 +00001323 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001324 return;
1325 }
Prabir Pradhanf192a102021-08-06 14:01:18 +00001326 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1327 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1328 return;
1329 }
1330
Vishnu Nairc519ff72021-01-21 08:23:08 -08001331 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1333 mWindowTokenWithPointerCapture = token;
1334 } else {
Prabir Pradhanf192a102021-08-06 14:01:18 +00001335 // Disable Pointer Capture.
1336 // We do not check if the sequence number matches for requests to disable Pointer Capture
1337 // for two reasons:
1338 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1339 // to disable capture with the same sequence number: one generated by
1340 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1341 // Capture being disabled in InputReader.
1342 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1343 // actual Pointer Capture state that affects events being generated by input devices is
1344 // in InputReader.
1345 if (!haveWindowWithPointerCapture) {
1346 // Pointer capture was already forcefully disabled because of focus change.
1347 dropReason = DropReason::NOT_DROPPED;
1348 return;
1349 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001350 token = mWindowTokenWithPointerCapture;
1351 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanf192a102021-08-06 14:01:18 +00001352 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001353 setPointerCaptureLocked(false);
1354 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001355 }
1356
1357 auto channel = getInputChannelLocked(token);
1358 if (channel == nullptr) {
1359 // Window has gone away, clean up Pointer Capture state.
1360 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanf192a102021-08-06 14:01:18 +00001361 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001362 setPointerCaptureLocked(false);
1363 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001364 return;
1365 }
1366 InputTarget target;
1367 target.inputChannel = channel;
1368 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1369 entry->dispatchInProgress = true;
1370 dispatchEventLocked(currentTime, entry, {target});
1371
1372 dropReason = DropReason::NOT_DROPPED;
1373}
1374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001375bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001376 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001378 if (!entry->dispatchInProgress) {
1379 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1380 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1381 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1382 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001383 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 // We have seen two identical key downs in a row which indicates that the device
1385 // driver is automatically generating key repeats itself. We take note of the
1386 // repeat here, but we disable our own next key repeat timer since it is clear that
1387 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001388 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1389 // Make sure we don't get key down from a different device. If a different
1390 // device Id has same key pressed down, the new device Id will replace the
1391 // current one to hold the key repeat with repeat count reset.
1392 // In the future when got a KEY_UP on the device id, drop it and do not
1393 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1395 resetKeyRepeatLocked();
1396 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1397 } else {
1398 // Not a repeat. Save key down state in case we do see a repeat later.
1399 resetKeyRepeatLocked();
1400 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1401 }
1402 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001403 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1404 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001405 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001406#if DEBUG_INBOUND_EVENT_DETAILS
1407 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1408#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 resetKeyRepeatLocked();
1411 }
1412
1413 if (entry->repeatCount == 1) {
1414 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1415 } else {
1416 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1417 }
1418
1419 entry->dispatchInProgress = true;
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 }
1423
1424 // Handle case where the policy asked us to try again later last time.
1425 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1426 if (currentTime < entry->interceptKeyWakeupTime) {
1427 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1428 *nextWakeupTime = entry->interceptKeyWakeupTime;
1429 }
1430 return false; // wait until next wakeup
1431 }
1432 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1433 entry->interceptKeyWakeupTime = 0;
1434 }
1435
1436 // Give the policy a chance to intercept the key.
1437 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1438 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001439 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001440 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001441 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001442 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001443 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001445 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 return false; // wait for the command to run
1447 } else {
1448 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1449 }
1450 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001451 if (*dropReason == DropReason::NOT_DROPPED) {
1452 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454 }
1455
1456 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001457 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001458 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001459 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1460 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001461 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 return true;
1463 }
1464
1465 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001466 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001469 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 return false;
1471 }
1472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return true;
1476 }
1477
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001478 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
1481 // Dispatch the key.
1482 dispatchEventLocked(currentTime, entry, inputTargets);
1483 return true;
1484}
1485
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001486void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001488 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001489 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1490 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001491 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1492 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1493 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494#endif
1495}
1496
Chris Yef59a2f42020-10-16 12:55:26 -07001497void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1498 mLock.unlock();
1499
1500 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1501 if (entry->accuracyChanged) {
1502 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1503 }
1504 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1505 entry->hwTimestamp, entry->values);
1506 mLock.lock();
1507}
1508
1509void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1510 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1511#if DEBUG_OUTBOUND_EVENT_DETAILS
1512 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1513 "source=0x%x, sensorType=%s",
1514 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001515 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001516#endif
1517 std::unique_ptr<CommandEntry> commandEntry =
1518 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1519 commandEntry->sensorEntry = entry;
1520 postCommandLocked(std::move(commandEntry));
1521}
1522
1523bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1524#if DEBUG_OUTBOUND_EVENT_DETAILS
1525 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1526 NamedEnum::string(sensorType).c_str());
1527#endif
1528 { // acquire lock
1529 std::scoped_lock _l(mLock);
1530
1531 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1532 std::shared_ptr<EventEntry> entry = *it;
1533 if (entry->type == EventEntry::Type::SENSOR) {
1534 it = mInboundQueue.erase(it);
1535 releaseInboundEventLocked(entry);
1536 }
1537 }
1538 }
1539 return true;
1540}
1541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001542bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001543 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001544 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001546 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 entry->dispatchInProgress = true;
1548
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551
1552 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001553 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1556 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return true;
1558 }
1559
1560 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1561
1562 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001563 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564
1565 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 if (isPointerEvent) {
1568 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001570 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001571 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 } else {
1573 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001574 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 return false;
1579 }
1580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001583 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1584 return true;
1585 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001587 CancelationOptions::Mode mode(isPointerEvent
1588 ? CancelationOptions::CANCEL_POINTER_EVENTS
1589 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1590 CancelationOptions options(mode, "input event injection failed");
1591 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 return true;
1593 }
1594
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001595 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001596 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001598 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001599 std::unordered_map<int32_t, TouchState>::iterator it =
1600 mTouchStatesByDisplay.find(entry->displayId);
1601 if (it != mTouchStatesByDisplay.end()) {
1602 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001603 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001604 // The event has gone through these portal windows, so we add monitoring targets of
1605 // the corresponding displays as well.
1606 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001607 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001608 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001609 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001610 }
1611 }
1612 }
1613 }
1614
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 // Dispatch the motion.
1616 if (conflictingPointerActions) {
1617 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 synthesizeCancelationEventsForAllConnectionsLocked(options);
1620 }
1621 dispatchEventLocked(currentTime, entry, inputTargets);
1622 return true;
1623}
1624
arthurhungb89ccb02020-12-30 16:19:01 +08001625void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1626 bool isExiting, const MotionEntry& motionEntry) {
1627 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1628 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1629 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1630 PointerCoords pointerCoords;
1631 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1632 pointerCoords.transform(windowHandle->getInfo()->transform);
1633
1634 std::unique_ptr<DragEntry> dragEntry =
1635 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1636 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1637 pointerCoords.getY());
1638
1639 enqueueInboundEventLocked(std::move(dragEntry));
1640}
1641
1642void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1643 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1644 if (channel == nullptr) {
1645 return; // Window has gone away
1646 }
1647 InputTarget target;
1648 target.inputChannel = channel;
1649 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1650 entry->dispatchInProgress = true;
1651 dispatchEventLocked(currentTime, entry, {target});
1652}
1653
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001656 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 ", policyFlags=0x%x, "
1658 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1659 "metaState=0x%x, buttonState=0x%x,"
1660 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001661 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1662 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1663 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001665 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001667 "x=%f, y=%f, pressure=%f, size=%f, "
1668 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1669 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1671 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1672 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1673 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1674 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1675 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1676 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1677 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1678 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1679 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 }
1681#endif
1682}
1683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001684void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1685 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001686 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001687 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688#if DEBUG_DISPATCH_CYCLE
1689 ALOGD("dispatchEventToCurrentInputTargets");
1690#endif
1691
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001692 updateInteractionTokensLocked(*eventEntry, inputTargets);
1693
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001698 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001699 sp<Connection> connection =
1700 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001701 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001702 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001704 if (DEBUG_FOCUS) {
1705 ALOGD("Dropping event delivery to target with channel '%s' because it "
1706 "is no longer registered with the input dispatcher.",
1707 inputTarget.inputChannel->getName().c_str());
1708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 }
1710 }
1711}
1712
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001713void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1714 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1715 // If the policy decides to close the app, we will get a channel removal event via
1716 // unregisterInputChannel, and will clean up the connection that way. We are already not
1717 // sending new pointers to the connection when it blocked, but focused events will continue to
1718 // pile up.
1719 ALOGW("Canceling events for %s because it is unresponsive",
1720 connection->inputChannel->getName().c_str());
1721 if (connection->status == Connection::STATUS_NORMAL) {
1722 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1723 "application not responding");
1724 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
1726}
1727
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001728void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001729 if (DEBUG_FOCUS) {
1730 ALOGD("Resetting ANR timeouts.");
1731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732
1733 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001734 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001735 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736}
1737
Tiger Huang721e26f2018-07-24 22:26:19 +08001738/**
1739 * Get the display id that the given event should go to. If this event specifies a valid display id,
1740 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1741 * Focused display is the display that the user most recently interacted with.
1742 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001743int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001744 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001745 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001746 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001747 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1748 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 break;
1750 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001751 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001752 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1753 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 break;
1755 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001756 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001757 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001758 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001759 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001760 case EventEntry::Type::SENSOR:
1761 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001762 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001763 return ADISPLAY_ID_NONE;
1764 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001765 }
1766 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1767}
1768
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001769bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1770 const char* focusedWindowName) {
1771 if (mAnrTracker.empty()) {
1772 // already processed all events that we waited for
1773 mKeyIsWaitingForEventsTimeout = std::nullopt;
1774 return false;
1775 }
1776
1777 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1778 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001779 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001780 mKeyIsWaitingForEventsTimeout = currentTime +
1781 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1782 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001783 return true;
1784 }
1785
1786 // We still have pending events, and already started the timer
1787 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1788 return true; // Still waiting
1789 }
1790
1791 // Waited too long, and some connection still hasn't processed all motions
1792 // Just send the key to the focused window
1793 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1794 focusedWindowName);
1795 mKeyIsWaitingForEventsTimeout = std::nullopt;
1796 return false;
1797}
1798
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001799InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1800 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1801 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001802 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803
Tiger Huang721e26f2018-07-24 22:26:19 +08001804 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001805 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001806 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001807 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1808
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 // If there is no currently focused window and no focused application
1810 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001811 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1812 ALOGI("Dropping %s event because there is no focused window or focused application in "
1813 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001814 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
1817
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1819 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1820 // start interacting with another application via touch (app switch). This code can be removed
1821 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1822 // an app is expected to have a focused window.
1823 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1824 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1825 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001826 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1827 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1828 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001830 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831 ALOGW("Waiting because no window has focus but %s may eventually add a "
1832 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001833 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001834 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1837 // Already raised ANR. Drop the event
1838 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001839 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 } else {
1842 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001844 }
1845 }
1846
1847 // we have a valid, non-null focused window
1848 resetNoFocusedWindowTimeoutLocked();
1849
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
1854
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001855 if (focusedWindowHandle->getInfo()->paused) {
1856 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001858 }
1859
1860 // If the event is a key event, then we must wait for all previous events to
1861 // complete before delivering it because previous events may have the
1862 // side-effect of transferring focus to a different window and we want to
1863 // ensure that the following keys are sent to the new window.
1864 //
1865 // Suppose the user touches a button in a window then immediately presses "A".
1866 // If the button causes a pop-up window to appear then we want to ensure that
1867 // the "A" key is delivered to the new pop-up window. This is because users
1868 // often anticipate pending UI changes when typing on a keyboard.
1869 // To obtain this behavior, we must serialize key events with respect to all
1870 // prior input events.
1871 if (entry.type == EventEntry::Type::KEY) {
1872 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1873 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
1877
1878 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001879 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1881 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882
1883 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885}
1886
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887/**
1888 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1889 * that are currently unresponsive.
1890 */
1891std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1892 const std::vector<TouchedMonitor>& monitors) const {
1893 std::vector<TouchedMonitor> responsiveMonitors;
1894 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1895 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1896 sp<Connection> connection = getConnectionLocked(
1897 monitor.monitor.inputChannel->getConnectionToken());
1898 if (connection == nullptr) {
1899 ALOGE("Could not find connection for monitor %s",
1900 monitor.monitor.inputChannel->getName().c_str());
1901 return false;
1902 }
1903 if (!connection->responsive) {
1904 ALOGW("Unresponsive monitor %s will not get the new gesture",
1905 connection->inputChannel->getName().c_str());
1906 return false;
1907 }
1908 return true;
1909 });
1910 return responsiveMonitors;
1911}
1912
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001913InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1914 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1915 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 enum InjectionPermission {
1918 INJECTION_PERMISSION_UNKNOWN,
1919 INJECTION_PERMISSION_GRANTED,
1920 INJECTION_PERMISSION_DENIED
1921 };
1922
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 // For security reasons, we defer updating the touch state until we are sure that
1924 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001925 int32_t displayId = entry.displayId;
1926 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1928
1929 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001930 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001932 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1933 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001935 // Copy current touch state into tempTouchState.
1936 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1937 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001938 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001940 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1941 mTouchStatesByDisplay.find(displayId);
1942 if (oldStateIt != mTouchStatesByDisplay.end()) {
1943 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001945 }
1946
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 bool isSplit = tempTouchState.split;
1948 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1949 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1950 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001951 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1952 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1953 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1954 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1955 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001956 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 bool wrongDevice = false;
1958 if (newGesture) {
1959 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001960 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001961 ALOGI("Dropping event because a pointer for a different device is already down "
1962 "in display %" PRId32,
1963 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001964 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 switchedDevice = false;
1967 wrongDevice = true;
1968 goto Failed;
1969 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001970 tempTouchState.reset();
1971 tempTouchState.down = down;
1972 tempTouchState.deviceId = entry.deviceId;
1973 tempTouchState.source = entry.source;
1974 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001976 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001977 ALOGI("Dropping move event because a pointer for a different device is already active "
1978 "in display %" PRId32,
1979 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001980 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001981 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001982 switchedDevice = false;
1983 wrongDevice = true;
1984 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
1986
1987 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1988 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1989
Garfield Tan00f511d2019-06-12 16:55:40 -07001990 int32_t x;
1991 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001993 // Always dispatch mouse events to cursor position.
1994 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001995 x = int32_t(entry.xCursorPosition);
1996 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001997 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001998 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1999 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002000 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002001 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07002002 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2004 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002005
2006 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002007 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002008 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002011 if (newTouchedWindowHandle != nullptr &&
2012 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002013 // New window supports splitting, but we should never split mouse events.
2014 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 } else if (isSplit) {
2016 // New window does not support splitting but we have already split events.
2017 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002018 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
2020
2021 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002022 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002024 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002025 }
2026
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2028 ALOGI("Not sending touch event to %s because it is paused",
2029 newTouchedWindowHandle->getName().c_str());
2030 newTouchedWindowHandle = nullptr;
2031 }
2032
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002033 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002034 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002035 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2036 if (!isResponsive) {
2037 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2039 newTouchedWindowHandle = nullptr;
2040 }
2041 }
2042
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002043 // Drop events that can't be trusted due to occlusion
2044 if (newTouchedWindowHandle != nullptr &&
2045 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2046 TouchOcclusionInfo occlusionInfo =
2047 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002048 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002049 if (DEBUG_TOUCH_OCCLUSION) {
2050 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2051 for (const auto& log : occlusionInfo.debugInfo) {
2052 ALOGD("%s", log.c_str());
2053 }
2054 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002055 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2056 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2057 ALOGW("Dropping untrusted touch event due to %s/%d",
2058 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2059 newTouchedWindowHandle = nullptr;
2060 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002061 }
2062 }
2063
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064 // Also don't send the new touch event to unresponsive gesture monitors
2065 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2066
Michael Wright3dd60e22019-03-27 22:06:44 +00002067 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2068 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 "(%d, %d) in display %" PRId32 ".",
2070 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002071 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 goto Failed;
2073 }
2074
2075 if (newTouchedWindowHandle != nullptr) {
2076 // Set target flags.
2077 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2078 if (isSplit) {
2079 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2082 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2083 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2084 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2085 }
2086
2087 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002088 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2089 newHoverWindowHandle = nullptr;
2090 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002091 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002092 }
2093
2094 // Update the temporary touch state.
2095 BitSet32 pointerIds;
2096 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002097 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002098 pointerIds.markBit(pointerId);
2099 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002103 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 } else {
2105 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2106
2107 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002108 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002109 if (DEBUG_FOCUS) {
2110 ALOGD("Dropping event because the pointer is not down or we previously "
2111 "dropped the pointer down event in display %" PRId32,
2112 displayId);
2113 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002114 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 goto Failed;
2116 }
2117
arthurhung6d4bed92021-03-17 11:59:33 +08002118 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002119
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002121 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2124 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
2126 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002128 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002129 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2130 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002131 if (DEBUG_FOCUS) {
2132 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2133 oldTouchedWindowHandle->getName().c_str(),
2134 newTouchedWindowHandle->getName().c_str(), displayId);
2135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002137 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2138 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2139 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
2141 // Make a slippery entrance into the new window.
2142 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2143 isSplit = true;
2144 }
2145
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002146 int32_t targetFlags =
2147 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 if (isSplit) {
2149 targetFlags |= InputTarget::FLAG_SPLIT;
2150 }
2151 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2152 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002153 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2154 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156
2157 BitSet32 pointerIds;
2158 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002161 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
2163 }
2164 }
2165
2166 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002167 // Let the previous window know that the hover sequence is over, unless we already did it
2168 // when dispatching it as is to newTouchedWindowHandle.
2169 if (mLastHoverWindowHandle != nullptr &&
2170 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2171 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172#if DEBUG_HOVER
2173 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2177 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 }
2179
Garfield Tandf26e862020-07-01 20:18:19 -07002180 // Let the new window know that the hover sequence is starting, unless we already did it
2181 // when dispatching it as is to newTouchedWindowHandle.
2182 if (newHoverWindowHandle != nullptr &&
2183 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2184 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185#if DEBUG_HOVER
2186 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002187 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2190 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2191 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
2193 }
2194
2195 // Check permission to inject into all touched foreground windows and ensure there
2196 // is at least one touched foreground window.
2197 {
2198 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002199 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2201 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002202 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002203 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 injectionPermission = INJECTION_PERMISSION_DENIED;
2205 goto Failed;
2206 }
2207 }
2208 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002209 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002210 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002211 ALOGI("Dropping event because there is no touched foreground window in display "
2212 "%" PRId32 " or gesture monitor to receive it.",
2213 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002214 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 goto Failed;
2216 }
2217
2218 // Permission granted to injection into all touched foreground windows.
2219 injectionPermission = INJECTION_PERMISSION_GRANTED;
2220 }
2221
2222 // Check whether windows listening for outside touches are owned by the same UID. If it is
2223 // set the policy flag that we will not reveal coordinate information to this window.
2224 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2225 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002226 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002227 if (foregroundWindowHandle) {
2228 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2231 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2232 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002233 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2234 InputTarget::FLAG_ZERO_COORDS,
2235 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
2238 }
2239 }
2240 }
2241
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // If this is the first pointer going down and the touched window has a wallpaper
2243 // then also add the touched wallpaper windows so they are locked in for the duration
2244 // of the touch gesture.
2245 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2246 // engine only supports touch events. We would need to add a mechanism similar
2247 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2248 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2249 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002251 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002252 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002253 getWindowHandlesLocked(displayId);
2254 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002257 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002258 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 .addOrUpdateWindow(windowHandle,
2260 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2261 InputTarget::
2262 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2263 InputTarget::FLAG_DISPATCH_AS_IS,
2264 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266 }
2267 }
2268 }
2269
2270 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002271 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002273 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002279 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002281 }
2282
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 // Drop the outside or hover touch windows since we will not care about them
2284 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002285 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287Failed:
2288 // Check injection permission once and for all.
2289 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002290 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 injectionPermission = INJECTION_PERMISSION_GRANTED;
2292 } else {
2293 injectionPermission = INJECTION_PERMISSION_DENIED;
2294 }
2295 }
2296
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002297 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2298 return injectionResult;
2299 }
2300
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002302 if (!wrongDevice) {
2303 if (switchedDevice) {
2304 if (DEBUG_FOCUS) {
2305 ALOGD("Conflicting pointer actions: Switched to a different device.");
2306 }
2307 *outConflictingPointerActions = true;
2308 }
2309
2310 if (isHoverAction) {
2311 // Started hovering, therefore no longer down.
2312 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002313 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002314 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2315 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 *outConflictingPointerActions = true;
2318 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002319 tempTouchState.reset();
2320 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2321 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2322 tempTouchState.deviceId = entry.deviceId;
2323 tempTouchState.source = entry.source;
2324 tempTouchState.displayId = displayId;
2325 }
2326 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2327 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2328 // All pointers up or canceled.
2329 tempTouchState.reset();
2330 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2331 // First pointer went down.
2332 if (oldState && oldState->down) {
2333 if (DEBUG_FOCUS) {
2334 ALOGD("Conflicting pointer actions: Down received while already down.");
2335 }
2336 *outConflictingPointerActions = true;
2337 }
2338 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2339 // One pointer went up.
2340 if (isSplit) {
2341 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2342 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002344 for (size_t i = 0; i < tempTouchState.windows.size();) {
2345 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2346 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2347 touchedWindow.pointerIds.clearBit(pointerId);
2348 if (touchedWindow.pointerIds.isEmpty()) {
2349 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2350 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002353 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002355 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002356 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002357
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 // Save changes unless the action was scroll in which case the temporary touch
2359 // state was only valid for this one action.
2360 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2361 if (tempTouchState.displayId >= 0) {
2362 mTouchStatesByDisplay[displayId] = tempTouchState;
2363 } else {
2364 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002368 // Update hover state.
2369 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 return injectionResult;
2373}
2374
arthurhung6d4bed92021-03-17 11:59:33 +08002375void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2376 const sp<InputWindowHandle> dropWindow =
2377 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2378 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2379 true /*ignoreDragWindow*/);
2380 if (dropWindow) {
2381 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2382 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002383 } else {
2384 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002385 }
2386 mDragState.reset();
2387}
2388
2389void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2390 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002391 return;
2392 }
2393
arthurhung6d4bed92021-03-17 11:59:33 +08002394 if (!mDragState->isStartDrag) {
2395 mDragState->isStartDrag = true;
2396 mDragState->isStylusButtonDownAtStart =
2397 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2398 }
2399
arthurhungb89ccb02020-12-30 16:19:01 +08002400 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2401 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2402 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2403 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002404 // Handle the special case : stylus button no longer pressed.
2405 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2406 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2407 finishDragAndDrop(entry.displayId, x, y);
2408 return;
2409 }
2410
arthurhungb89ccb02020-12-30 16:19:01 +08002411 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002412 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002413 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2414 true /*ignoreDragWindow*/);
2415 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002416 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2417 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2418 if (mDragState->dragHoverWindowHandle != nullptr) {
2419 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2420 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002421 }
arthurhung6d4bed92021-03-17 11:59:33 +08002422 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002423 }
2424 // enqueue drag location if needed.
2425 if (hoverWindowHandle != nullptr) {
2426 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2427 }
arthurhung6d4bed92021-03-17 11:59:33 +08002428 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2429 finishDragAndDrop(entry.displayId, x, y);
2430 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002431 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002432 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002433 }
2434}
2435
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002437 int32_t targetFlags, BitSet32 pointerIds,
2438 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439 std::vector<InputTarget>::iterator it =
2440 std::find_if(inputTargets.begin(), inputTargets.end(),
2441 [&windowHandle](const InputTarget& inputTarget) {
2442 return inputTarget.inputChannel->getConnectionToken() ==
2443 windowHandle->getToken();
2444 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002445
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002446 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002447
2448 if (it == inputTargets.end()) {
2449 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002450 std::shared_ptr<InputChannel> inputChannel =
2451 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002452 if (inputChannel == nullptr) {
2453 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2454 return;
2455 }
2456 inputTarget.inputChannel = inputChannel;
2457 inputTarget.flags = targetFlags;
2458 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002459 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002460 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002461 inputTargets.push_back(inputTarget);
2462 it = inputTargets.end() - 1;
2463 }
2464
2465 ALOG_ASSERT(it->flags == targetFlags);
2466 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2467
chaviw1ff3d1e2020-07-01 15:53:47 -07002468 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469}
2470
Michael Wright3dd60e22019-03-27 22:06:44 +00002471void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002472 int32_t displayId, float xOffset,
2473 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002474 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2475 mGlobalMonitorsByDisplay.find(displayId);
2476
2477 if (it != mGlobalMonitorsByDisplay.end()) {
2478 const std::vector<Monitor>& monitors = it->second;
2479 for (const Monitor& monitor : monitors) {
2480 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
2483}
2484
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2486 float yOffset,
2487 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002488 InputTarget target;
2489 target.inputChannel = monitor.inputChannel;
2490 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002491 ui::Transform t;
2492 t.set(xOffset, yOffset);
2493 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002494 inputTargets.push_back(target);
2495}
2496
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498 const InjectionState* injectionState) {
2499 if (injectionState &&
2500 (windowHandle == nullptr ||
2501 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2502 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002503 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002505 "owned by uid %d",
2506 injectionState->injectorPid, injectionState->injectorUid,
2507 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 } else {
2509 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002510 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
2512 return false;
2513 }
2514 return true;
2515}
2516
Robert Carrc9bf1d32020-04-13 17:21:08 -07002517/**
2518 * Indicate whether one window handle should be considered as obscuring
2519 * another window handle. We only check a few preconditions. Actually
2520 * checking the bounds is left to the caller.
2521 */
2522static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2523 const sp<InputWindowHandle>& otherHandle) {
2524 // Compare by token so cloned layers aren't counted
2525 if (haveSameToken(windowHandle, otherHandle)) {
2526 return false;
2527 }
2528 auto info = windowHandle->getInfo();
2529 auto otherInfo = otherHandle->getInfo();
2530 if (!otherInfo->visible) {
2531 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002532 } else if (otherInfo->alpha == 0 &&
2533 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2534 // Those act as if they were invisible, so we don't need to flag them.
2535 // We do want to potentially flag touchable windows even if they have 0
2536 // opacity, since they can consume touches and alter the effects of the
2537 // user interaction (eg. apps that rely on
2538 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2539 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2540 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002541 } else if (info->ownerUid == otherInfo->ownerUid) {
2542 // If ownerUid is the same we don't generate occlusion events as there
2543 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002544 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002545 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002546 return false;
2547 } else if (otherInfo->displayId != info->displayId) {
2548 return false;
2549 }
2550 return true;
2551}
2552
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002553/**
2554 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2555 * untrusted, one should check:
2556 *
2557 * 1. If result.hasBlockingOcclusion is true.
2558 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2559 * BLOCK_UNTRUSTED.
2560 *
2561 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2562 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2563 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2564 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2565 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2566 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2567 *
2568 * If neither of those is true, then it means the touch can be allowed.
2569 */
2570InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2571 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002572 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2573 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002574 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2575 TouchOcclusionInfo info;
2576 info.hasBlockingOcclusion = false;
2577 info.obscuringOpacity = 0;
2578 info.obscuringUid = -1;
2579 std::map<int32_t, float> opacityByUid;
2580 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2581 if (windowHandle == otherHandle) {
2582 break; // All future windows are below us. Exit early.
2583 }
2584 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002585 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2586 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002587 if (DEBUG_TOUCH_OCCLUSION) {
2588 info.debugInfo.push_back(
2589 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2590 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002591 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2592 // we perform the checks below to see if the touch can be propagated or not based on the
2593 // window's touch occlusion mode
2594 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2595 info.hasBlockingOcclusion = true;
2596 info.obscuringUid = otherInfo->ownerUid;
2597 info.obscuringPackage = otherInfo->packageName;
2598 break;
2599 }
2600 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2601 uint32_t uid = otherInfo->ownerUid;
2602 float opacity =
2603 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2604 // Given windows A and B:
2605 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2606 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2607 opacityByUid[uid] = opacity;
2608 if (opacity > info.obscuringOpacity) {
2609 info.obscuringOpacity = opacity;
2610 info.obscuringUid = uid;
2611 info.obscuringPackage = otherInfo->packageName;
2612 }
2613 }
2614 }
2615 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002616 if (DEBUG_TOUCH_OCCLUSION) {
2617 info.debugInfo.push_back(
2618 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2619 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002620 return info;
2621}
2622
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002623std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2624 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002625 return StringPrintf(INDENT2
2626 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2627 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2628 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2629 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002630 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002631 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002632 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002633 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2634 info->frameTop, info->frameRight, info->frameBottom,
2635 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002636 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2637 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2638 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002639}
2640
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002641bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2642 if (occlusionInfo.hasBlockingOcclusion) {
2643 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2644 occlusionInfo.obscuringUid);
2645 return false;
2646 }
2647 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2648 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2649 "%.2f, maximum allowed = %.2f)",
2650 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2651 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2652 return false;
2653 }
2654 return true;
2655}
2656
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2658 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002660 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002661 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002662 if (windowHandle == otherHandle) {
2663 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002666 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002667 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 return true;
2669 }
2670 }
2671 return false;
2672}
2673
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002674bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2675 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002676 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002677 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002678 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002679 if (windowHandle == otherHandle) {
2680 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002681 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002682 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002684 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002685 return true;
2686 }
2687 }
2688 return false;
2689}
2690
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002691std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002692 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002694 if (applicationHandle != nullptr) {
2695 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002696 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 } else {
2698 return applicationHandle->getName();
2699 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002700 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002701 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002703 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 }
2705}
2706
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002707void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002708 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002709 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2710 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002711 // Focus or pointer capture changed events are passed to apps, but do not represent user
2712 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002713 return;
2714 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002715 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002716 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002717 if (focusedWindowHandle != nullptr) {
2718 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002719 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002721 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722#endif
2723 return;
2724 }
2725 }
2726
2727 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002728 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002729 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002730 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2731 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 return;
2733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002735 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 eventType = USER_ACTIVITY_EVENT_TOUCH;
2737 }
2738 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002740 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002741 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2742 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002743 return;
2744 }
2745 eventType = USER_ACTIVITY_EVENT_BUTTON;
2746 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002748 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002749 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002750 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002751 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002752 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2753 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002754 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002755 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002756 break;
2757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 }
2759
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002760 std::unique_ptr<CommandEntry> commandEntry =
2761 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002762 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002764 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002765 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766}
2767
2768void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002770 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002771 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002772 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002774 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002775 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002776 ATRACE_NAME(message.c_str());
2777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778#if DEBUG_DISPATCH_CYCLE
2779 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002780 "globalScaleFactor=%f, pointerIds=0x%x %s",
2781 connection->getInputChannelName().c_str(), inputTarget.flags,
2782 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2783 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784#endif
2785
2786 // Skip this event if the connection status is not normal.
2787 // We don't want to enqueue additional outbound events if the connection is broken.
2788 if (connection->status != Connection::STATUS_NORMAL) {
2789#if DEBUG_DISPATCH_CYCLE
2790 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792#endif
2793 return;
2794 }
2795
2796 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002797 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2798 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2799 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002800 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002802 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002803 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002804 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002805 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 if (!splitMotionEntry) {
2807 return; // split event was dropped
2808 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002809 if (DEBUG_FOCUS) {
2810 ALOGD("channel '%s' ~ Split motion event.",
2811 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002812 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002813 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002814 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2815 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 return;
2817 }
2818 }
2819
2820 // Not splitting. Enqueue dispatch entries for the event as is.
2821 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2822}
2823
2824void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002825 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002826 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002827 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002828 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002830 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002831 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002832 ATRACE_NAME(message.c_str());
2833 }
2834
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002835 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836
2837 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002840 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002844 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002846 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002848 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850
2851 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002852 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 startDispatchCycleLocked(currentTime, connection);
2854 }
2855}
2856
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002858 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002859 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002860 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002861 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002862 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2863 connection->getInputChannelName().c_str(),
2864 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002865 ATRACE_NAME(message.c_str());
2866 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002867 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 if (!(inputTargetFlags & dispatchMode)) {
2869 return;
2870 }
2871 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2872
2873 // This is a new event.
2874 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002875 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002876 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002878 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2879 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002880 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002882 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002883 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002884 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002885 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002886 dispatchEntry->resolvedAction = keyEntry.action;
2887 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2890 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2893 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 return; // skip the inconsistent event
2896 }
2897 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002900 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002901 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002902 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2903 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2904 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2905 static_cast<int32_t>(IdGenerator::Source::OTHER);
2906 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002907 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2908 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2909 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2910 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2911 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2912 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2913 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2914 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2915 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2916 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2917 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002918 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002919 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 }
2921 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002922 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2923 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2926 "event",
2927 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002929 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2930 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002934 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2936 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2937 }
2938 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2939 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002942 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2943 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2946 "event",
2947 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 return; // skip the inconsistent event
2950 }
2951
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002952 dispatchEntry->resolvedEventId =
2953 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2954 ? mIdGenerator.nextId()
2955 : motionEntry.id;
2956 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2957 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2958 ") to MotionEvent(id=0x%" PRIx32 ").",
2959 motionEntry.id, dispatchEntry->resolvedEventId);
2960 ATRACE_NAME(message.c_str());
2961 }
2962
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002963 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2964 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2965 // Skip reporting pointer down outside focus to the policy.
2966 break;
2967 }
2968
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002969 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002970 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971
2972 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002974 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002975 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2976 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002977 break;
2978 }
Chris Yef59a2f42020-10-16 12:55:26 -07002979 case EventEntry::Type::SENSOR: {
2980 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2981 break;
2982 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002983 case EventEntry::Type::CONFIGURATION_CHANGED:
2984 case EventEntry::Type::DEVICE_RESET: {
2985 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002986 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002987 break;
2988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989 }
2990
2991 // Remember that we are waiting for this dispatch to complete.
2992 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002993 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995
2996 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002997 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002998 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002999}
3000
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003001/**
3002 * This function is purely for debugging. It helps us understand where the user interaction
3003 * was taking place. For example, if user is touching launcher, we will see a log that user
3004 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3005 * We will see both launcher and wallpaper in that list.
3006 * Once the interaction with a particular set of connections starts, no new logs will be printed
3007 * until the set of interacted connections changes.
3008 *
3009 * The following items are skipped, to reduce the logspam:
3010 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3011 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3012 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3013 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3014 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003015 */
3016void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3017 const std::vector<InputTarget>& targets) {
3018 // Skip ACTION_UP events, and all events other than keys and motions
3019 if (entry.type == EventEntry::Type::KEY) {
3020 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3021 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3022 return;
3023 }
3024 } else if (entry.type == EventEntry::Type::MOTION) {
3025 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3026 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3027 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3028 return;
3029 }
3030 } else {
3031 return; // Not a key or a motion
3032 }
3033
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003034 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003035 std::vector<sp<Connection>> newConnections;
3036 for (const InputTarget& target : targets) {
3037 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3038 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3039 continue; // Skip windows that receive ACTION_OUTSIDE
3040 }
3041
3042 sp<IBinder> token = target.inputChannel->getConnectionToken();
3043 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003044 if (connection == nullptr) {
3045 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003046 }
3047 newConnectionTokens.insert(std::move(token));
3048 newConnections.emplace_back(connection);
3049 }
3050 if (newConnectionTokens == mInteractionConnectionTokens) {
3051 return; // no change
3052 }
3053 mInteractionConnectionTokens = newConnectionTokens;
3054
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003055 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003056 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003057 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003058 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003059 std::string message = "Interaction with: " + targetList;
3060 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003061 message += "<none>";
3062 }
3063 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3064}
3065
chaviwfd6d3512019-03-25 13:23:49 -07003066void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003067 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003068 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003069 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3070 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003071 return;
3072 }
3073
Vishnu Nairc519ff72021-01-21 08:23:08 -08003074 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003075 if (focusedToken == token) {
3076 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003077 return;
3078 }
3079
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003080 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3081 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003082 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003083 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084}
3085
3086void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003088 if (ATRACE_ENABLED()) {
3089 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003091 ATRACE_NAME(message.c_str());
3092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095#endif
3096
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003097 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3098 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003100 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003101 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003102 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
3104 // Publish the event.
3105 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003106 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3107 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003108 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003109 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3110 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003113 status = connection->inputPublisher
3114 .publishKeyEvent(dispatchEntry->seq,
3115 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3116 keyEntry.source, keyEntry.displayId,
3117 std::move(hmac), dispatchEntry->resolvedAction,
3118 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3119 keyEntry.scanCode, keyEntry.metaState,
3120 keyEntry.repeatCount, keyEntry.downTime,
3121 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123 }
3124
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003125 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003129 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003130
chaviw82357092020-01-28 13:13:06 -08003131 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003132 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3134 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003135 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003136 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3137 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003138 // Don't apply window scale here since we don't want scale to affect raw
3139 // coordinates. The scale will be sent back to the client and applied
3140 // later when requesting relative coordinates.
3141 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3142 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 }
3144 usingCoords = scaledCoords;
3145 }
3146 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003147 // We don't want the dispatch target to know.
3148 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003149 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 scaledCoords[i].clear();
3151 }
3152 usingCoords = scaledCoords;
3153 }
3154 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003155
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003156 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157
3158 // Publish the motion event.
3159 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003160 .publishMotionEvent(dispatchEntry->seq,
3161 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 motionEntry.deviceId, motionEntry.source,
3163 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003164 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003166 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003167 motionEntry.edgeFlags, motionEntry.metaState,
3168 motionEntry.buttonState,
3169 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003170 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003171 motionEntry.xPrecision, motionEntry.yPrecision,
3172 motionEntry.xCursorPosition,
3173 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003174 dispatchEntry->displaySize.x,
3175 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003176 motionEntry.downTime, motionEntry.eventTime,
3177 motionEntry.pointerCount,
3178 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 break;
3180 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003181
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003182 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003183 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003184 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003185 focusEntry.id,
3186 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003187 mInTouchMode);
3188 break;
3189 }
3190
Prabir Pradhan99987712020-11-10 18:43:05 -08003191 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3192 const auto& captureEntry =
3193 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3194 status = connection->inputPublisher
3195 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhanf192a102021-08-06 14:01:18 +00003196 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003197 break;
3198 }
3199
arthurhungb89ccb02020-12-30 16:19:01 +08003200 case EventEntry::Type::DRAG: {
3201 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3202 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3203 dragEntry.id, dragEntry.x,
3204 dragEntry.y,
3205 dragEntry.isExiting);
3206 break;
3207 }
3208
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003209 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003210 case EventEntry::Type::DEVICE_RESET:
3211 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003212 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003213 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003214 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 }
3217
3218 // Check the result.
3219 if (status) {
3220 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003221 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 "This is unexpected because the wait queue is empty, so the pipe "
3224 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003225 "event to it, status=%s(%d)",
3226 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3227 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3229 } else {
3230 // Pipe is full and we are waiting for the app to finish process some events
3231 // before sending more events to it.
3232#if DEBUG_DISPATCH_CYCLE
3233 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 "waiting for the application to catch up",
3235 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 }
3238 } else {
3239 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003240 "status=%s(%d)",
3241 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3242 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3244 }
3245 return;
3246 }
3247
3248 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003249 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3250 connection->outboundQueue.end(),
3251 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003252 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003253 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003254 if (connection->responsive) {
3255 mAnrTracker.insert(dispatchEntry->timeoutTime,
3256 connection->inputChannel->getConnectionToken());
3257 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003258 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 }
3260}
3261
chaviw09c8d2d2020-08-24 15:48:26 -07003262std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3263 size_t size;
3264 switch (event.type) {
3265 case VerifiedInputEvent::Type::KEY: {
3266 size = sizeof(VerifiedKeyEvent);
3267 break;
3268 }
3269 case VerifiedInputEvent::Type::MOTION: {
3270 size = sizeof(VerifiedMotionEvent);
3271 break;
3272 }
3273 }
3274 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3275 return mHmacKeyManager.sign(start, size);
3276}
3277
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003278const std::array<uint8_t, 32> InputDispatcher::getSignature(
3279 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3280 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3281 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3282 // Only sign events up and down events as the purely move events
3283 // are tied to their up/down counterparts so signing would be redundant.
3284 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3285 verifiedEvent.actionMasked = actionMasked;
3286 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003287 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003288 }
3289 return INVALID_HMAC;
3290}
3291
3292const std::array<uint8_t, 32> InputDispatcher::getSignature(
3293 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3294 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3295 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3296 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003297 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003298}
3299
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003302 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303#if DEBUG_DISPATCH_CYCLE
3304 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306#endif
3307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 if (connection->status == Connection::STATUS_BROKEN ||
3309 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 return;
3311 }
3312
3313 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003314 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315}
3316
3317void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 const sp<Connection>& connection,
3319 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320#if DEBUG_DISPATCH_CYCLE
3321 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323#endif
3324
3325 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003326 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003327 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003328 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003329 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
3331 // The connection appears to be unrecoverably broken.
3332 // Ignore already broken or zombie connections.
3333 if (connection->status == Connection::STATUS_NORMAL) {
3334 connection->status = Connection::STATUS_BROKEN;
3335
3336 if (notify) {
3337 // Notify other system components.
3338 onDispatchCycleBrokenLocked(currentTime, connection);
3339 }
3340 }
3341}
3342
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003343void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3344 while (!queue.empty()) {
3345 DispatchEntry* dispatchEntry = queue.front();
3346 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003347 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 }
3349}
3350
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003351void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003353 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 }
3355 delete dispatchEntry;
3356}
3357
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003358int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3359 std::scoped_lock _l(mLock);
3360 sp<Connection> connection = getConnectionLocked(connectionToken);
3361 if (connection == nullptr) {
3362 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3363 connectionToken.get(), events);
3364 return 0; // remove the callback
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003367 bool notify;
3368 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3369 if (!(events & ALOOPER_EVENT_INPUT)) {
3370 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3371 "events=0x%x",
3372 connection->getInputChannelName().c_str(), events);
3373 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
3375
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003376 nsecs_t currentTime = now();
3377 bool gotOne = false;
3378 status_t status = OK;
3379 for (;;) {
3380 Result<InputPublisher::ConsumerResponse> result =
3381 connection->inputPublisher.receiveConsumerResponse();
3382 if (!result.ok()) {
3383 status = result.error().code();
3384 break;
3385 }
3386
3387 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3388 const InputPublisher::Finished& finish =
3389 std::get<InputPublisher::Finished>(*result);
3390 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3391 finish.consumeTime);
3392 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003393 if (shouldReportMetricsForConnection(*connection)) {
3394 const InputPublisher::Timeline& timeline =
3395 std::get<InputPublisher::Timeline>(*result);
3396 mLatencyTracker
3397 .trackGraphicsLatency(timeline.inputEventId,
3398 connection->inputChannel->getConnectionToken(),
3399 std::move(timeline.graphicsTimeline));
3400 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003401 }
3402 gotOne = true;
3403 }
3404 if (gotOne) {
3405 runCommandsLockedInterruptible();
3406 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 return 1;
3408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
3410
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003411 notify = status != DEAD_OBJECT || !connection->monitor;
3412 if (notify) {
3413 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3414 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3415 status);
3416 }
3417 } else {
3418 // Monitor channels are never explicitly unregistered.
3419 // We do it automatically when the remote endpoint is closed so don't warn about them.
3420 const bool stillHaveWindowHandle =
3421 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3422 notify = !connection->monitor && stillHaveWindowHandle;
3423 if (notify) {
3424 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3425 connection->getInputChannelName().c_str(), events);
3426 }
3427 }
3428
3429 // Remove the channel.
3430 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3431 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432}
3433
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003436 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003437 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 }
3439}
3440
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003442 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003443 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3444 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3445}
3446
3447void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3448 const CancelationOptions& options,
3449 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3450 for (const auto& it : monitorsByDisplay) {
3451 const std::vector<Monitor>& monitors = it.second;
3452 for (const Monitor& monitor : monitors) {
3453 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003454 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003455 }
3456}
3457
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003459 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003460 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003461 if (connection == nullptr) {
3462 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003464
3465 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466}
3467
3468void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3469 const sp<Connection>& connection, const CancelationOptions& options) {
3470 if (connection->status == Connection::STATUS_BROKEN) {
3471 return;
3472 }
3473
3474 nsecs_t currentTime = now();
3475
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003476 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003477 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003479 if (cancelationEvents.empty()) {
3480 return;
3481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003483 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3484 "with reality: %s, mode=%d.",
3485 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3486 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003488
3489 InputTarget target;
3490 sp<InputWindowHandle> windowHandle =
3491 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3492 if (windowHandle != nullptr) {
3493 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003494 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003495 target.globalScaleFactor = windowInfo->globalScaleFactor;
3496 }
3497 target.inputChannel = connection->inputChannel;
3498 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3499
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003500 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003501 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003502 switch (cancelationEventEntry->type) {
3503 case EventEntry::Type::KEY: {
3504 logOutboundKeyDetails("cancel - ",
3505 static_cast<const KeyEntry&>(*cancelationEventEntry));
3506 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003508 case EventEntry::Type::MOTION: {
3509 logOutboundMotionDetails("cancel - ",
3510 static_cast<const MotionEntry&>(*cancelationEventEntry));
3511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003513 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3515 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003516 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003517 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003518 break;
3519 }
3520 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003521 case EventEntry::Type::DEVICE_RESET:
3522 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003523 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003524 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003525 break;
3526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003529 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3530 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003532
3533 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534}
3535
Svet Ganov5d3bc372020-01-26 23:11:07 -08003536void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3537 const sp<Connection>& connection) {
3538 if (connection->status == Connection::STATUS_BROKEN) {
3539 return;
3540 }
3541
3542 nsecs_t currentTime = now();
3543
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003544 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003545 connection->inputState.synthesizePointerDownEvents(currentTime);
3546
3547 if (downEvents.empty()) {
3548 return;
3549 }
3550
3551#if DEBUG_OUTBOUND_EVENT_DETAILS
3552 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3553 connection->getInputChannelName().c_str(), downEvents.size());
3554#endif
3555
3556 InputTarget target;
3557 sp<InputWindowHandle> windowHandle =
3558 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3559 if (windowHandle != nullptr) {
3560 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003561 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003562 target.globalScaleFactor = windowInfo->globalScaleFactor;
3563 }
3564 target.inputChannel = connection->inputChannel;
3565 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003567 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003568 switch (downEventEntry->type) {
3569 case EventEntry::Type::MOTION: {
3570 logOutboundMotionDetails("down - ",
3571 static_cast<const MotionEntry&>(*downEventEntry));
3572 break;
3573 }
3574
3575 case EventEntry::Type::KEY:
3576 case EventEntry::Type::FOCUS:
3577 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003578 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003579 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003580 case EventEntry::Type::SENSOR:
3581 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003583 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003584 break;
3585 }
3586 }
3587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003588 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3589 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003590 }
3591
3592 startDispatchCycleLocked(currentTime, connection);
3593}
3594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3596 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 ALOG_ASSERT(pointerIds.value != 0);
3598
3599 uint32_t splitPointerIndexMap[MAX_POINTERS];
3600 PointerProperties splitPointerProperties[MAX_POINTERS];
3601 PointerCoords splitPointerCoords[MAX_POINTERS];
3602
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003603 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 uint32_t splitPointerCount = 0;
3605
3606 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003609 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 uint32_t pointerId = uint32_t(pointerProperties.id);
3611 if (pointerIds.hasBit(pointerId)) {
3612 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3613 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3614 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003615 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 splitPointerCount += 1;
3617 }
3618 }
3619
3620 if (splitPointerCount != pointerIds.count()) {
3621 // This is bad. We are missing some of the pointers that we expected to deliver.
3622 // Most likely this indicates that we received an ACTION_MOVE events that has
3623 // different pointer ids than we expected based on the previous ACTION_DOWN
3624 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3625 // in this way.
3626 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 "we expected there to be %d pointers. This probably means we received "
3628 "a broken sequence of pointer ids from the input device.",
3629 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003630 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 }
3632
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003633 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003635 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3636 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3638 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003639 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 uint32_t pointerId = uint32_t(pointerProperties.id);
3641 if (pointerIds.hasBit(pointerId)) {
3642 if (pointerIds.count() == 1) {
3643 // The first/last pointer went down/up.
3644 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003645 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003646 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3647 ? AMOTION_EVENT_ACTION_CANCEL
3648 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 } else {
3650 // A secondary pointer went down/up.
3651 uint32_t splitPointerIndex = 0;
3652 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3653 splitPointerIndex += 1;
3654 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003655 action = maskedAction |
3656 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658 } else {
3659 // An unrelated pointer changed.
3660 action = AMOTION_EVENT_ACTION_MOVE;
3661 }
3662 }
3663
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003664 int32_t newId = mIdGenerator.nextId();
3665 if (ATRACE_ENABLED()) {
3666 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3667 ") to MotionEvent(id=0x%" PRIx32 ").",
3668 originalMotionEntry.id, newId);
3669 ATRACE_NAME(message.c_str());
3670 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003671 std::unique_ptr<MotionEntry> splitMotionEntry =
3672 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3673 originalMotionEntry.deviceId, originalMotionEntry.source,
3674 originalMotionEntry.displayId,
3675 originalMotionEntry.policyFlags, action,
3676 originalMotionEntry.actionButton,
3677 originalMotionEntry.flags, originalMotionEntry.metaState,
3678 originalMotionEntry.buttonState,
3679 originalMotionEntry.classification,
3680 originalMotionEntry.edgeFlags,
3681 originalMotionEntry.xPrecision,
3682 originalMotionEntry.yPrecision,
3683 originalMotionEntry.xCursorPosition,
3684 originalMotionEntry.yCursorPosition,
3685 originalMotionEntry.downTime, splitPointerCount,
3686 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003688 if (originalMotionEntry.injectionState) {
3689 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 splitMotionEntry->injectionState->refCount += 1;
3691 }
3692
3693 return splitMotionEntry;
3694}
3695
3696void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3697#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003698 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699#endif
3700
3701 bool needWake;
3702 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003703 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003705 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3706 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3707 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 } // release lock
3709
3710 if (needWake) {
3711 mLooper->wake();
3712 }
3713}
3714
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003715/**
3716 * If one of the meta shortcuts is detected, process them here:
3717 * Meta + Backspace -> generate BACK
3718 * Meta + Enter -> generate HOME
3719 * This will potentially overwrite keyCode and metaState.
3720 */
3721void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003723 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3724 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3725 if (keyCode == AKEYCODE_DEL) {
3726 newKeyCode = AKEYCODE_BACK;
3727 } else if (keyCode == AKEYCODE_ENTER) {
3728 newKeyCode = AKEYCODE_HOME;
3729 }
3730 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003731 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003732 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003733 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003734 keyCode = newKeyCode;
3735 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3736 }
3737 } else if (action == AKEY_EVENT_ACTION_UP) {
3738 // In order to maintain a consistent stream of up and down events, check to see if the key
3739 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3740 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003741 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003742 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003743 auto replacementIt = mReplacedKeys.find(replacement);
3744 if (replacementIt != mReplacedKeys.end()) {
3745 keyCode = replacementIt->second;
3746 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003747 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3748 }
3749 }
3750}
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3753#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3755 "policyFlags=0x%x, action=0x%x, "
3756 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3757 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3758 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3759 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760#endif
3761 if (!validateKeyEvent(args->action)) {
3762 return;
3763 }
3764
3765 uint32_t policyFlags = args->policyFlags;
3766 int32_t flags = args->flags;
3767 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003768 // InputDispatcher tracks and generates key repeats on behalf of
3769 // whatever notifies it, so repeatCount should always be set to 0
3770 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3772 policyFlags |= POLICY_FLAG_VIRTUAL;
3773 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 if (policyFlags & POLICY_FLAG_FUNCTION) {
3776 metaState |= AMETA_FUNCTION_ON;
3777 }
3778
3779 policyFlags |= POLICY_FLAG_TRUSTED;
3780
Michael Wright78f24442014-08-06 15:55:28 -07003781 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003782 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003783
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003785 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003786 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3787 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788
Michael Wright2b3c3302018-03-02 17:19:13 +00003789 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003791 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3792 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 bool needWake;
3797 { // acquire lock
3798 mLock.lock();
3799
3800 if (shouldSendKeyToInputFilterLocked(args)) {
3801 mLock.unlock();
3802
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003803 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3805 return; // event was consumed by the filter
3806 }
3807
3808 mLock.lock();
3809 }
3810
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003811 std::unique_ptr<KeyEntry> newEntry =
3812 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3813 args->displayId, policyFlags, args->action, flags,
3814 keyCode, args->scanCode, metaState, repeatCount,
3815 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003817 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 mLock.unlock();
3819 } // release lock
3820
3821 if (needWake) {
3822 mLooper->wake();
3823 }
3824}
3825
3826bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3827 return mInputFilterEnabled;
3828}
3829
3830void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3831#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003832 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3833 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003834 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3835 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003836 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003837 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3838 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3839 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3840 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 for (uint32_t i = 0; i < args->pointerCount; i++) {
3842 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003843 "x=%f, y=%f, pressure=%f, size=%f, "
3844 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3845 "orientation=%f",
3846 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3847 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3848 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3849 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3850 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3851 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3852 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3853 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3854 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3855 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 }
3857#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003858 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3859 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 return;
3861 }
3862
3863 uint32_t policyFlags = args->policyFlags;
3864 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003865
3866 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003867 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003868 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3869 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003870 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872
3873 bool needWake;
3874 { // acquire lock
3875 mLock.lock();
3876
3877 if (shouldSendMotionToInputFilterLocked(args)) {
3878 mLock.unlock();
3879
3880 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003881 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003882 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3883 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003884 args->metaState, args->buttonState, args->classification, transform,
3885 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003886 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3887 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003888 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889
3890 policyFlags |= POLICY_FLAG_FILTERED;
3891 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3892 return; // event was consumed by the filter
3893 }
3894
3895 mLock.lock();
3896 }
3897
3898 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003899 std::unique_ptr<MotionEntry> newEntry =
3900 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3901 args->source, args->displayId, policyFlags,
3902 args->action, args->actionButton, args->flags,
3903 args->metaState, args->buttonState,
3904 args->classification, args->edgeFlags,
3905 args->xPrecision, args->yPrecision,
3906 args->xCursorPosition, args->yCursorPosition,
3907 args->downTime, args->pointerCount,
3908 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003910 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 mLock.unlock();
3912 } // release lock
3913
3914 if (needWake) {
3915 mLooper->wake();
3916 }
3917}
3918
Chris Yef59a2f42020-10-16 12:55:26 -07003919void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3920#if DEBUG_INBOUND_EVENT_DETAILS
3921 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3922 " sensorType=%s",
3923 args->id, args->eventTime, args->deviceId, args->source,
3924 NamedEnum::string(args->sensorType).c_str());
3925#endif
3926
3927 bool needWake;
3928 { // acquire lock
3929 mLock.lock();
3930
3931 // Just enqueue a new sensor event.
3932 std::unique_ptr<SensorEntry> newEntry =
3933 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3934 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3935 args->sensorType, args->accuracy,
3936 args->accuracyChanged, args->values);
3937
3938 needWake = enqueueInboundEventLocked(std::move(newEntry));
3939 mLock.unlock();
3940 } // release lock
3941
3942 if (needWake) {
3943 mLooper->wake();
3944 }
3945}
3946
Chris Yefb552902021-02-03 17:18:37 -08003947void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3948#if DEBUG_INBOUND_EVENT_DETAILS
3949 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3950 args->deviceId, args->isOn);
3951#endif
3952 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3953}
3954
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003956 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957}
3958
3959void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3960#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003961 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 "switchMask=0x%08x",
3963 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964#endif
3965
3966 uint32_t policyFlags = args->policyFlags;
3967 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003968 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969}
3970
3971void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3972#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3974 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975#endif
3976
3977 bool needWake;
3978 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003979 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003981 std::unique_ptr<DeviceResetEntry> newEntry =
3982 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3983 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 } // release lock
3985
3986 if (needWake) {
3987 mLooper->wake();
3988 }
3989}
3990
Prabir Pradhan7e186182020-11-10 13:56:45 -08003991void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3992#if DEBUG_INBOUND_EVENT_DETAILS
3993 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhanf192a102021-08-06 14:01:18 +00003994 args->request.enable ? "true" : "false");
Prabir Pradhan7e186182020-11-10 13:56:45 -08003995#endif
3996
Prabir Pradhan99987712020-11-10 18:43:05 -08003997 bool needWake;
3998 { // acquire lock
3999 std::scoped_lock _l(mLock);
4000 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhanf192a102021-08-06 14:01:18 +00004001 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004002 needWake = enqueueInboundEventLocked(std::move(entry));
4003 } // release lock
4004
4005 if (needWake) {
4006 mLooper->wake();
4007 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004008}
4009
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004010InputEventInjectionResult InputDispatcher::injectInputEvent(
4011 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4012 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013#if DEBUG_INBOUND_EVENT_DETAILS
4014 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004015 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4016 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004018 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
4020 policyFlags |= POLICY_FLAG_INJECTED;
4021 if (hasInjectionPermission(injectorPid, injectorUid)) {
4022 policyFlags |= POLICY_FLAG_TRUSTED;
4023 }
4024
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004025 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004026 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4027 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4028 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4029 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4030 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004031 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004032 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004033 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004034 }
4035
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004039 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4040 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004041 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004045 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004046 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4047 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4048 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004049 int32_t keyCode = incomingKey.getKeyCode();
4050 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004051 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004053 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004054 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004055 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4056 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4057 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4060 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062
4063 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4064 android::base::Timer t;
4065 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4066 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4067 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4068 std::to_string(t.duration().count()).c_str());
4069 }
4070 }
4071
4072 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004073 std::unique_ptr<KeyEntry> injectedEntry =
4074 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004075 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004076 incomingKey.getDisplayId(), policyFlags, action,
4077 flags, keyCode, incomingKey.getScanCode(), metaState,
4078 incomingKey.getRepeatCount(),
4079 incomingKey.getDownTime());
4080 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 }
4083
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004084 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004085 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4086 int32_t action = motionEvent.getAction();
4087 size_t pointerCount = motionEvent.getPointerCount();
4088 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4089 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004090 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004091 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004093 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 }
4095
4096 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004097 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004098 android::base::Timer t;
4099 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4100 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4101 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4102 std::to_string(t.duration().count()).c_str());
4103 }
4104 }
4105
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004106 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4107 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4108 }
4109
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004111 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4112 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004113 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004114 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4115 resolvedDeviceId, motionEvent.getSource(),
4116 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004117 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004118 motionEvent.getButtonState(),
4119 motionEvent.getClassification(),
4120 motionEvent.getEdgeFlags(),
4121 motionEvent.getXPrecision(),
4122 motionEvent.getYPrecision(),
4123 motionEvent.getRawXCursorPosition(),
4124 motionEvent.getRawYCursorPosition(),
4125 motionEvent.getDownTime(), uint32_t(pointerCount),
4126 pointerProperties, samplePointerCoords,
4127 motionEvent.getXOffset(),
4128 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004129 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 sampleEventTimes += 1;
4132 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004133 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004134 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4135 resolvedDeviceId, motionEvent.getSource(),
4136 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004137 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004138 motionEvent.getMetaState(),
4139 motionEvent.getButtonState(),
4140 motionEvent.getClassification(),
4141 motionEvent.getEdgeFlags(),
4142 motionEvent.getXPrecision(),
4143 motionEvent.getYPrecision(),
4144 motionEvent.getRawXCursorPosition(),
4145 motionEvent.getRawYCursorPosition(),
4146 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004147 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004148 samplePointerCoords, motionEvent.getXOffset(),
4149 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004150 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 }
4152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004156 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004157 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159
4160 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004161 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 injectionState->injectionIsAsync = true;
4163 }
4164
4165 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004166 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
4168 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004169 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004170 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004171 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
4173
4174 mLock.unlock();
4175
4176 if (needWake) {
4177 mLooper->wake();
4178 }
4179
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004180 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004182 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004184 if (syncMode == InputEventInjectionSync::NONE) {
4185 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 } else {
4187 for (;;) {
4188 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004189 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 }
4192
4193 nsecs_t remainingTimeout = endTime - now();
4194 if (remainingTimeout <= 0) {
4195#if DEBUG_INJECTION
4196 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004199 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 break;
4201 }
4202
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004203 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 }
4205
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004206 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4207 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 while (injectionState->pendingForegroundDispatches != 0) {
4209#if DEBUG_INJECTION
4210 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212#endif
4213 nsecs_t remainingTimeout = endTime - now();
4214 if (remainingTimeout <= 0) {
4215#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4217 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 break;
4221 }
4222
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004223 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 }
4225 }
4226 }
4227
4228 injectionState->release();
4229 } // release lock
4230
4231#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004232 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234#endif
4235
4236 return injectionResult;
4237}
4238
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004239std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004240 std::array<uint8_t, 32> calculatedHmac;
4241 std::unique_ptr<VerifiedInputEvent> result;
4242 switch (event.getType()) {
4243 case AINPUT_EVENT_TYPE_KEY: {
4244 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4245 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4246 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004247 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004248 break;
4249 }
4250 case AINPUT_EVENT_TYPE_MOTION: {
4251 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4252 VerifiedMotionEvent verifiedMotionEvent =
4253 verifiedMotionEventFromMotionEvent(motionEvent);
4254 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004255 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004256 break;
4257 }
4258 default: {
4259 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4260 return nullptr;
4261 }
4262 }
4263 if (calculatedHmac == INVALID_HMAC) {
4264 return nullptr;
4265 }
4266 if (calculatedHmac != event.getHmac()) {
4267 return nullptr;
4268 }
4269 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004270}
4271
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 return injectorUid == 0 ||
4274 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275}
4276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004277void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004278 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 if (injectionState) {
4281#if DEBUG_INJECTION
4282 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 "injectorPid=%d, injectorUid=%d",
4284 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285#endif
4286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 // Log the outcome since the injector did not wait for the injection result.
4289 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004290 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 ALOGV("Asynchronous input event injection succeeded.");
4292 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004293 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 ALOGW("Asynchronous input event injection failed.");
4295 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004296 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 ALOGW("Asynchronous input event injection permission denied.");
4298 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004299 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 ALOGW("Asynchronous input event injection timed out.");
4301 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004302 case InputEventInjectionResult::PENDING:
4303 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306 }
4307
4308 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004309 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311}
4312
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4314 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 if (injectionState) {
4316 injectionState->pendingForegroundDispatches += 1;
4317 }
4318}
4319
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004320void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4321 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 if (injectionState) {
4323 injectionState->pendingForegroundDispatches -= 1;
4324
4325 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004326 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328 }
4329}
4330
Vishnu Nairad321cd2020-08-20 16:40:21 -07004331const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004332 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004333 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4334 auto it = mWindowHandlesByDisplay.find(displayId);
4335 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004336}
4337
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004339 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004340 if (windowHandleToken == nullptr) {
4341 return nullptr;
4342 }
4343
Arthur Hungb92218b2018-08-14 12:00:21 +08004344 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004345 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004346 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004347 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004348 return windowHandle;
4349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
4351 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004352 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353}
4354
Vishnu Nairad321cd2020-08-20 16:40:21 -07004355sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4356 int displayId) const {
4357 if (windowHandleToken == nullptr) {
4358 return nullptr;
4359 }
4360
4361 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4362 if (windowHandle->getToken() == windowHandleToken) {
4363 return windowHandle;
4364 }
4365 }
4366 return nullptr;
4367}
4368
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004369sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4370 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004371 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004372 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004373 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004374 if (handle->getId() == windowHandle->getId() &&
4375 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004376 if (windowHandle->getInfo()->displayId != it.first) {
4377 ALOGE("Found window %s in display %" PRId32
4378 ", but it should belong to display %" PRId32,
4379 windowHandle->getName().c_str(), it.first,
4380 windowHandle->getInfo()->displayId);
4381 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004382 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004386 return nullptr;
4387}
4388
4389sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4390 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4391 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392}
4393
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004394bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4395 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4396 const bool noInputChannel =
4397 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4398 if (connection != nullptr && noInputChannel) {
4399 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4400 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4401 return false;
4402 }
4403
4404 if (connection == nullptr) {
4405 if (!noInputChannel) {
4406 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4407 }
4408 return false;
4409 }
4410 if (!connection->responsive) {
4411 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4412 return false;
4413 }
4414 return true;
4415}
4416
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004417std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4418 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004419 auto connectionIt = mConnectionsByToken.find(token);
4420 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004421 return nullptr;
4422 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004423 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004424}
4425
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004426void InputDispatcher::updateWindowHandlesForDisplayLocked(
4427 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4428 if (inputWindowHandles.empty()) {
4429 // Remove all handles on a display if there are no windows left.
4430 mWindowHandlesByDisplay.erase(displayId);
4431 return;
4432 }
4433
4434 // Since we compare the pointer of input window handles across window updates, we need
4435 // to make sure the handle object for the same window stays unchanged across updates.
4436 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004437 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004438 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004439 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004440 }
4441
4442 std::vector<sp<InputWindowHandle>> newHandles;
4443 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4444 if (!handle->updateInfo()) {
4445 // handle no longer valid
4446 continue;
4447 }
4448
4449 const InputWindowInfo* info = handle->getInfo();
4450 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4451 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4452 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004453 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4454 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4455 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004456 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004457 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004458 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004459 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004460 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004461 }
4462
4463 if (info->displayId != displayId) {
4464 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4465 handle->getName().c_str(), displayId, info->displayId);
4466 continue;
4467 }
4468
Robert Carredd13602020-04-13 17:24:34 -07004469 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4470 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004471 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004472 oldHandle->updateFrom(handle);
4473 newHandles.push_back(oldHandle);
4474 } else {
4475 newHandles.push_back(handle);
4476 }
4477 }
4478
4479 // Insert or replace
4480 mWindowHandlesByDisplay[displayId] = newHandles;
4481}
4482
Arthur Hung72d8dc32020-03-28 00:48:39 +00004483void InputDispatcher::setInputWindows(
4484 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4485 { // acquire lock
4486 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004487 for (const auto& [displayId, handles] : handlesPerDisplay) {
4488 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004489 }
4490 }
4491 // Wake up poll loop since it may need to make new input dispatching choices.
4492 mLooper->wake();
4493}
4494
Arthur Hungb92218b2018-08-14 12:00:21 +08004495/**
4496 * Called from InputManagerService, update window handle list by displayId that can receive input.
4497 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4498 * If set an empty list, remove all handles from the specific display.
4499 * For focused handle, check if need to change and send a cancel event to previous one.
4500 * For removed handle, check if need to send a cancel event if already in touch.
4501 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004502void InputDispatcher::setInputWindowsLocked(
4503 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004504 if (DEBUG_FOCUS) {
4505 std::string windowList;
4506 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4507 windowList += iwh->getName() + " ";
4508 }
4509 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004512 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4513 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4514 const bool noInputWindow =
4515 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4516 if (noInputWindow && window->getToken() != nullptr) {
4517 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4518 window->getName().c_str());
4519 window->releaseChannel();
4520 }
4521 }
4522
Arthur Hung72d8dc32020-03-28 00:48:39 +00004523 // Copy old handles for release if they are no longer present.
4524 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004526 // Save the old windows' orientation by ID before it gets updated.
4527 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4528 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4529 oldWindowOrientations.emplace(handle->getId(),
4530 handle->getInfo()->transform.getOrientation());
4531 }
4532
Arthur Hung72d8dc32020-03-28 00:48:39 +00004533 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004534
Vishnu Nair958da932020-08-21 17:12:37 -07004535 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4536 if (mLastHoverWindowHandle &&
4537 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4538 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004539 mLastHoverWindowHandle = nullptr;
4540 }
4541
Vishnu Nairc519ff72021-01-21 08:23:08 -08004542 std::optional<FocusResolver::FocusChanges> changes =
4543 mFocusResolver.setInputWindows(displayId, windowHandles);
4544 if (changes) {
4545 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004548 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4549 mTouchStatesByDisplay.find(displayId);
4550 if (stateIt != mTouchStatesByDisplay.end()) {
4551 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004552 for (size_t i = 0; i < state.windows.size();) {
4553 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004554 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004555 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004556 ALOGD("Touched window was removed: %s in display %" PRId32,
4557 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004558 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004559 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004560 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4561 if (touchedInputChannel != nullptr) {
4562 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4563 "touched window was removed");
4564 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004566 state.windows.erase(state.windows.begin() + i);
4567 } else {
4568 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 }
4570 }
arthurhungb89ccb02020-12-30 16:19:01 +08004571
arthurhung6d4bed92021-03-17 11:59:33 +08004572 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004573 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004574 if (mDragState &&
4575 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004576 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004577 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004578 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004579 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004580
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004581 if (isPerWindowInputRotationEnabled()) {
4582 // Determine if the orientation of any of the input windows have changed, and cancel all
4583 // pointer events if necessary.
4584 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4585 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4586 if (newWindowHandle != nullptr &&
4587 newWindowHandle->getInfo()->transform.getOrientation() !=
4588 oldWindowOrientations[oldWindowHandle->getId()]) {
4589 std::shared_ptr<InputChannel> inputChannel =
4590 getInputChannelLocked(newWindowHandle->getToken());
4591 if (inputChannel != nullptr) {
4592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4593 "touched window's orientation changed");
4594 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4595 }
4596 }
4597 }
4598 }
4599
Arthur Hung72d8dc32020-03-28 00:48:39 +00004600 // Release information for windows that are no longer present.
4601 // This ensures that unused input channels are released promptly.
4602 // Otherwise, they might stick around until the window handle is destroyed
4603 // which might not happen until the next GC.
4604 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004605 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606 if (DEBUG_FOCUS) {
4607 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004608 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004609 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004610 // To avoid making too many calls into the compat framework, only
4611 // check for window flags when windows are going away.
4612 // TODO(b/157929241) : delete this. This is only needed temporarily
4613 // in order to gather some data about the flag usage
4614 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4615 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4616 oldWindowHandle->getName().c_str());
4617 if (mCompatService != nullptr) {
4618 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4619 oldWindowHandle->getInfo()->ownerUid);
4620 }
4621 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004622 }
chaviw291d88a2019-02-14 10:33:58 -08004623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624}
4625
4626void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004627 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004628 if (DEBUG_FOCUS) {
4629 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4630 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4631 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004632 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004633 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004634 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 } // release lock
4636
4637 // Wake up poll loop since it may need to make new input dispatching choices.
4638 mLooper->wake();
4639}
4640
Vishnu Nair599f1412021-06-21 10:39:58 -07004641void InputDispatcher::setFocusedApplicationLocked(
4642 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4643 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4644 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4645
4646 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4647 return; // This application is already focused. No need to wake up or change anything.
4648 }
4649
4650 // Set the new application handle.
4651 if (inputApplicationHandle != nullptr) {
4652 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4653 } else {
4654 mFocusedApplicationHandlesByDisplay.erase(displayId);
4655 }
4656
4657 // No matter what the old focused application was, stop waiting on it because it is
4658 // no longer focused.
4659 resetNoFocusedWindowTimeoutLocked();
4660}
4661
Tiger Huang721e26f2018-07-24 22:26:19 +08004662/**
4663 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4664 * the display not specified.
4665 *
4666 * We track any unreleased events for each window. If a window loses the ability to receive the
4667 * released event, we will send a cancel event to it. So when the focused display is changed, we
4668 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4669 * display. The display-specified events won't be affected.
4670 */
4671void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004672 if (DEBUG_FOCUS) {
4673 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4674 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004675 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004676 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004677
4678 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004679 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004680 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004681 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004682 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004683 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004684 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 CancelationOptions
4686 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4687 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004688 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004689 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4690 }
4691 }
4692 mFocusedDisplayId = displayId;
4693
Chris Ye3c2d6f52020-08-09 10:39:48 -07004694 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004695 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004696 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004697
Vishnu Nairad321cd2020-08-20 16:40:21 -07004698 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004699 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004700 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004701 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004702 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004703 }
4704 }
4705 }
4706
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004707 if (DEBUG_FOCUS) {
4708 logDispatchStateLocked();
4709 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004710 } // release lock
4711
4712 // Wake up poll loop since it may need to make new input dispatching choices.
4713 mLooper->wake();
4714}
4715
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004717 if (DEBUG_FOCUS) {
4718 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720
4721 bool changed;
4722 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004723 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
4725 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4726 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729
4730 if (mDispatchEnabled && !enabled) {
4731 resetAndDropEverythingLocked("dispatcher is being disabled");
4732 }
4733
4734 mDispatchEnabled = enabled;
4735 mDispatchFrozen = frozen;
4736 changed = true;
4737 } else {
4738 changed = false;
4739 }
4740
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004741 if (DEBUG_FOCUS) {
4742 logDispatchStateLocked();
4743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 } // release lock
4745
4746 if (changed) {
4747 // Wake up poll loop since it may need to make new input dispatching choices.
4748 mLooper->wake();
4749 }
4750}
4751
4752void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004753 if (DEBUG_FOCUS) {
4754 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756
4757 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004758 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759
4760 if (mInputFilterEnabled == enabled) {
4761 return;
4762 }
4763
4764 mInputFilterEnabled = enabled;
4765 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4766 } // release lock
4767
4768 // Wake up poll loop since there might be work to do to drop everything.
4769 mLooper->wake();
4770}
4771
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004772void InputDispatcher::setInTouchMode(bool inTouchMode) {
4773 std::scoped_lock lock(mLock);
4774 mInTouchMode = inTouchMode;
4775}
4776
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004777void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4778 if (opacity < 0 || opacity > 1) {
4779 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4780 return;
4781 }
4782
4783 std::scoped_lock lock(mLock);
4784 mMaximumObscuringOpacityForTouch = opacity;
4785}
4786
4787void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4788 std::scoped_lock lock(mLock);
4789 mBlockUntrustedTouchesMode = mode;
4790}
4791
arthurhungb89ccb02020-12-30 16:19:01 +08004792bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4793 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004794 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004795 if (DEBUG_FOCUS) {
4796 ALOGD("Trivial transfer to same window.");
4797 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004798 return true;
4799 }
4800
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004802 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
chaviwfbe5d9c2018-12-26 12:23:37 -08004804 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4805 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004806 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004807 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 return false;
4809 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004810 if (DEBUG_FOCUS) {
4811 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4812 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004815 if (DEBUG_FOCUS) {
4816 ALOGD("Cannot transfer focus because windows are on different displays.");
4817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 return false;
4819 }
4820
4821 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004822 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4823 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004824 for (size_t i = 0; i < state.windows.size(); i++) {
4825 const TouchedWindow& touchedWindow = state.windows[i];
4826 if (touchedWindow.windowHandle == fromWindowHandle) {
4827 int32_t oldTargetFlags = touchedWindow.targetFlags;
4828 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004830 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 int32_t newTargetFlags = oldTargetFlags &
4833 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4834 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004835 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836
arthurhungb89ccb02020-12-30 16:19:01 +08004837 // Store the dragging window.
4838 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004839 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004840 }
4841
Jeff Brownf086ddb2014-02-11 14:28:48 -08004842 found = true;
4843 goto Found;
4844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004850 if (DEBUG_FOCUS) {
4851 ALOGD("Focus transfer failed because from window did not have focus.");
4852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 return false;
4854 }
4855
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004856 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4857 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004858 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004859 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860 CancelationOptions
4861 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4862 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004864 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004867 if (DEBUG_FOCUS) {
4868 logDispatchStateLocked();
4869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 } // release lock
4871
4872 // Wake up poll loop since it may need to make new input dispatching choices.
4873 mLooper->wake();
4874 return true;
4875}
4876
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004877// Binder call
4878bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4879 sp<IBinder> fromToken;
4880 { // acquire lock
4881 std::scoped_lock _l(mLock);
4882
4883 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4884 if (toWindowHandle == nullptr) {
4885 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4886 return false;
4887 }
4888
4889 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4890
4891 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4892 if (touchStateIt == mTouchStatesByDisplay.end()) {
4893 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4894 displayId);
4895 return false;
4896 }
4897
4898 TouchState& state = touchStateIt->second;
4899 if (state.windows.size() != 1) {
4900 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4901 state.windows.size());
4902 return false;
4903 }
4904 const TouchedWindow& touchedWindow = state.windows[0];
4905 fromToken = touchedWindow.windowHandle->getToken();
4906 } // release lock
4907
4908 return transferTouchFocus(fromToken, destChannelToken);
4909}
4910
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004912 if (DEBUG_FOCUS) {
4913 ALOGD("Resetting and dropping all events (%s).", reason);
4914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
4916 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4917 synthesizeCancelationEventsForAllConnectionsLocked(options);
4918
4919 resetKeyRepeatLocked();
4920 releasePendingEventLocked();
4921 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004922 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004925 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004927 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928}
4929
4930void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004931 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 dumpDispatchStateLocked(dump);
4933
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004934 std::istringstream stream(dump);
4935 std::string line;
4936
4937 while (std::getline(stream, line, '\n')) {
4938 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 }
4940}
4941
Prabir Pradhan99987712020-11-10 18:43:05 -08004942std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4943 std::string dump;
4944
Prabir Pradhanf192a102021-08-06 14:01:18 +00004945 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
4946 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08004947
4948 std::string windowName = "None";
4949 if (mWindowTokenWithPointerCapture) {
4950 const sp<InputWindowHandle> captureWindowHandle =
4951 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4952 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4953 : "token has capture without window";
4954 }
Prabir Pradhanf192a102021-08-06 14:01:18 +00004955 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08004956
4957 return dump;
4958}
4959
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004960void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004961 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4962 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4963 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004964 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
Tiger Huang721e26f2018-07-24 22:26:19 +08004966 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4967 dump += StringPrintf(INDENT "FocusedApplications:\n");
4968 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4969 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004970 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004971 const std::chrono::duration timeout =
4972 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004973 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004974 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004975 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004978 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004980
Vishnu Nairc519ff72021-01-21 08:23:08 -08004981 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004982 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004984 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004985 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004986 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4987 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004988 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 state.displayId, toString(state.down), toString(state.split),
4990 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004991 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004992 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004993 for (size_t i = 0; i < state.windows.size(); i++) {
4994 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 dump += StringPrintf(INDENT4
4996 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4997 i, touchedWindow.windowHandle->getName().c_str(),
4998 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004999 }
5000 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005001 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005002 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005003 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005004 dump += INDENT3 "Portal windows:\n";
5005 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005006 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5008 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005009 }
5010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005013 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015
arthurhung6d4bed92021-03-17 11:59:33 +08005016 if (mDragState) {
5017 dump += StringPrintf(INDENT "DragState:\n");
5018 mDragState->dump(dump, INDENT2);
5019 }
5020
Arthur Hungb92218b2018-08-14 12:00:21 +08005021 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005023 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005024 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005025 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005026 dump += INDENT2 "Windows:\n";
5027 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005028 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08005029 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005031 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005032 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005033 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005034 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005035 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005036 "applicationInfo.name=%s, "
5037 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005038 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005039 i, windowInfo->name.c_str(), windowInfo->id,
5040 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005042 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005043 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005044 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005045 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005046 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005047 windowInfo->frameLeft, windowInfo->frameTop,
5048 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005049 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005050 windowInfo->applicationInfo.name.c_str(),
5051 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005052 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005053 dump += StringPrintf(", inputFeatures=%s",
5054 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005055 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005056 "ms, trustedOverlay=%s, hasToken=%s, "
5057 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005059 millis(windowInfo->dispatchingTimeout),
5060 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005061 toString(windowInfo->token != nullptr),
5062 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005063 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005064 }
5065 } else {
5066 dump += INDENT2 "Windows: <none>\n";
5067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 }
5069 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005070 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
5072
Michael Wright3dd60e22019-03-27 22:06:44 +00005073 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005074 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 const std::vector<Monitor>& monitors = it.second;
5076 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5077 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005078 }
5079 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005080 const std::vector<Monitor>& monitors = it.second;
5081 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5082 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005085 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087
5088 nsecs_t currentTime = now();
5089
5090 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005091 if (!mRecentQueue.empty()) {
5092 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005093 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005094 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005095 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005096 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 }
5098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101
5102 // Dump event currently being dispatched.
5103 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005104 dump += INDENT "PendingEvent:\n";
5105 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005106 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005107 dump += StringPrintf(", age=%" PRId64 "ms\n",
5108 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005110 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 }
5112
5113 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005114 if (!mInboundQueue.empty()) {
5115 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005116 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005117 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005118 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005119 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 }
5121 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005122 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 }
5124
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005125 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005126 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005127 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5128 const KeyReplacement& replacement = pair.first;
5129 int32_t newKeyCode = pair.second;
5130 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005131 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005132 }
5133 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005134 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005135 }
5136
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005137 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005138 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005139 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005141 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005142 connection->inputChannel->getFd().get(),
5143 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005144 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005145 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005147 if (!connection->outboundQueue.empty()) {
5148 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5149 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005150 dump += dumpQueue(connection->outboundQueue, currentTime);
5151
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005153 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005156 if (!connection->waitQueue.empty()) {
5157 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5158 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005159 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005161 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163 }
5164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167
5168 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5170 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005175 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005176 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5177 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5178 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005179 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005180 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
Michael Wright3dd60e22019-03-27 22:06:44 +00005183void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5184 const size_t numMonitors = monitors.size();
5185 for (size_t i = 0; i < numMonitors; i++) {
5186 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005187 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005188 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5189 dump += "\n";
5190 }
5191}
5192
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005193class LooperEventCallback : public LooperCallback {
5194public:
5195 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5196 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5197
5198private:
5199 std::function<int(int events)> mCallback;
5200};
5201
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005202Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005203#if DEBUG_CHANNEL_CREATION
5204 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205#endif
5206
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005207 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005208 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005209 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005210
5211 if (result) {
5212 return base::Error(result) << "Failed to open input channel pair with name " << name;
5213 }
5214
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005216 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005217 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005218 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005219 sp<Connection> connection =
5220 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005222 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5223 ALOGE("Created a new connection, but the token %p is already known", token.get());
5224 }
5225 mConnectionsByToken.emplace(token, connection);
5226
5227 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5228 this, std::placeholders::_1, token);
5229
5230 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 } // release lock
5232
5233 // Wake the looper because some connections have changed.
5234 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005235 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236}
5237
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005238Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5239 bool isGestureMonitor,
5240 const std::string& name,
5241 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005242 std::shared_ptr<InputChannel> serverChannel;
5243 std::unique_ptr<InputChannel> clientChannel;
5244 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5245 if (result) {
5246 return base::Error(result) << "Failed to open input channel pair with name " << name;
5247 }
5248
Michael Wright3dd60e22019-03-27 22:06:44 +00005249 { // acquire lock
5250 std::scoped_lock _l(mLock);
5251
5252 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005253 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5254 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005255 }
5256
Garfield Tan15601662020-09-22 15:32:38 -07005257 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005258 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005259 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005260
5261 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5262 ALOGE("Created a new connection, but the token %p is already known", token.get());
5263 }
5264 mConnectionsByToken.emplace(token, connection);
5265 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5266 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 auto& monitorsByDisplay =
5269 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005270 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005271
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005273 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5274 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005275 }
Garfield Tan15601662020-09-22 15:32:38 -07005276
Michael Wright3dd60e22019-03-27 22:06:44 +00005277 // Wake the looper because some connections have changed.
5278 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005279 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005280}
5281
Garfield Tan15601662020-09-22 15:32:38 -07005282status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005284 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285
Garfield Tan15601662020-09-22 15:32:38 -07005286 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 if (status) {
5288 return status;
5289 }
5290 } // release lock
5291
5292 // Wake the poll loop because removing the connection may have changed the current
5293 // synchronization state.
5294 mLooper->wake();
5295 return OK;
5296}
5297
Garfield Tan15601662020-09-22 15:32:38 -07005298status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5299 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005300 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005301 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005302 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 return BAD_VALUE;
5304 }
5305
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005306 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005307
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005309 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005312 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 nsecs_t currentTime = now();
5315 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5316
5317 connection->status = Connection::STATUS_ZOMBIE;
5318 return OK;
5319}
5320
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005321void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5322 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5323 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005324}
5325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005326void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005327 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005328 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005329 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005330 std::vector<Monitor>& monitors = it->second;
5331 const size_t numMonitors = monitors.size();
5332 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005333 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005334 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5335 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005336 monitors.erase(monitors.begin() + i);
5337 break;
5338 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005339 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 if (monitors.empty()) {
5341 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005342 } else {
5343 ++it;
5344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 }
5346}
5347
Michael Wright3dd60e22019-03-27 22:06:44 +00005348status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5349 { // acquire lock
5350 std::scoped_lock _l(mLock);
5351 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5352
5353 if (!foundDisplayId) {
5354 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5355 return BAD_VALUE;
5356 }
5357 int32_t displayId = foundDisplayId.value();
5358
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005359 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5360 mTouchStatesByDisplay.find(displayId);
5361 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005362 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5363 return BAD_VALUE;
5364 }
5365
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005366 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005367 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005368 std::optional<int32_t> foundDeviceId;
5369 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005370 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005371 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005372 foundDeviceId = state.deviceId;
5373 }
5374 }
5375 if (!foundDeviceId || !state.down) {
5376 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005377 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005378 return BAD_VALUE;
5379 }
5380 int32_t deviceId = foundDeviceId.value();
5381
5382 // Send cancel events to all the input channels we're stealing from.
5383 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 options.deviceId = deviceId;
5386 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005387 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005388 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005389 std::shared_ptr<InputChannel> channel =
5390 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005391 if (channel != nullptr) {
5392 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005393 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005394 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005395 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005396 canceledWindows += "]";
5397 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5398 canceledWindows.c_str());
5399
Michael Wright3dd60e22019-03-27 22:06:44 +00005400 // Then clear the current touch state so we stop dispatching to them as well.
5401 state.filterNonMonitors();
5402 }
5403 return OK;
5404}
5405
Prabir Pradhan99987712020-11-10 18:43:05 -08005406void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5407 { // acquire lock
5408 std::scoped_lock _l(mLock);
5409 if (DEBUG_FOCUS) {
5410 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5411 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5412 windowHandle != nullptr ? windowHandle->getName().c_str()
5413 : "token without window");
5414 }
5415
Vishnu Nairc519ff72021-01-21 08:23:08 -08005416 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005417 if (focusedToken != windowToken) {
5418 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5419 enabled ? "enable" : "disable");
5420 return;
5421 }
5422
Prabir Pradhanf192a102021-08-06 14:01:18 +00005423 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005424 ALOGW("Ignoring request to %s Pointer Capture: "
5425 "window has %s requested pointer capture.",
5426 enabled ? "enable" : "disable", enabled ? "already" : "not");
5427 return;
5428 }
5429
Prabir Pradhan99987712020-11-10 18:43:05 -08005430 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() {
Prabir Pradhanf192a102021-08-06 14:01:18 +00006188 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006189 return;
6190 }
6191
6192 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6193
Prabir Pradhanf192a102021-08-06 14:01:18 +00006194 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006195 setPointerCaptureLocked(false);
6196 }
6197
6198 if (!mWindowTokenWithPointerCapture) {
6199 // No need to send capture changes because no window has capture.
6200 return;
6201 }
6202
6203 if (mPendingEvent != nullptr) {
6204 // Move the pending event to the front of the queue. This will give the chance
6205 // for the pending event to be dropped if it is a captured event.
6206 mInboundQueue.push_front(mPendingEvent);
6207 mPendingEvent = nullptr;
6208 }
6209
6210 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhanf192a102021-08-06 14:01:18 +00006211 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006212 mInboundQueue.push_front(std::move(entry));
6213}
6214
Prabir Pradhan99987712020-11-10 18:43:05 -08006215void InputDispatcher::setPointerCaptureLocked(bool enabled) {
Prabir Pradhanf192a102021-08-06 14:01:18 +00006216 mCurrentPointerCaptureRequest.enable = enabled;
6217 mCurrentPointerCaptureRequest.seq++;
Prabir Pradhan99987712020-11-10 18:43:05 -08006218 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6219 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
Prabir Pradhanf192a102021-08-06 14:01:18 +00006220 commandEntry->pointerCaptureRequest = mCurrentPointerCaptureRequest;
Prabir Pradhan99987712020-11-10 18:43:05 -08006221 postCommandLocked(std::move(commandEntry));
6222}
6223
6224void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6225 android::inputdispatcher::CommandEntry* commandEntry) {
6226 mLock.unlock();
6227
Prabir Pradhanf192a102021-08-06 14:01:18 +00006228 mPolicy->setPointerCapture(commandEntry->pointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006229
6230 mLock.lock();
6231}
6232
Vishnu Nair599f1412021-06-21 10:39:58 -07006233void InputDispatcher::displayRemoved(int32_t displayId) {
6234 { // acquire lock
6235 std::scoped_lock _l(mLock);
6236 // Set an empty list to remove all handles from the specific display.
6237 setInputWindowsLocked(/* window handles */ {}, displayId);
6238 setFocusedApplicationLocked(displayId, nullptr);
6239 // Call focus resolver to clean up stale requests. This must be called after input windows
6240 // have been removed for the removed display.
6241 mFocusResolver.displayRemoved(displayId);
6242 } // release lock
6243
6244 // Wake up poll loop since it may need to make new input dispatching choices.
6245 mLooper->wake();
6246}
6247
Garfield Tane84e6f92019-08-29 17:28:41 -07006248} // namespace android::inputdispatcher