blob: 16abd483e67a74c947a6ebc7ff8c500a221f62c6 [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 <statslog.h>
63#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wright44753b12020-07-08 13:48:11 +010066#include <cerrno>
67#include <cinttypes>
68#include <climits>
69#include <cstddef>
70#include <ctime>
71#include <queue>
72#include <sstream>
73
74#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070075#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010076
Michael Wrightd02c5b62014-02-10 15:10:22 -080077#define INDENT " "
78#define INDENT2 " "
79#define INDENT3 " "
80#define INDENT4 " "
81
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000083using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080084using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080085using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080087using android::os::InputEventInjectionResult;
88using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100089using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080090
Garfield Tane84e6f92019-08-29 17:28:41 -070091namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Prabir Pradhan93a0f912021-04-21 13:47:42 -070093// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
94// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
95static bool isPerWindowInputRotationEnabled() {
96 static const bool PER_WINDOW_INPUT_ROTATION =
97 base::GetBoolProperty("persist.debug.per_window_input_rotation", false);
98 return PER_WINDOW_INPUT_ROTATION;
99}
100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101// Default input dispatching timeout if there is no focused application or paused window
102// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800103const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
104 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
105 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106
107// Amount of time to allow for all pending events to be processed when an app switch
108// key is on the way. This is used to preempt input dispatch and drop input events
109// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000110constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111
112// Amount of time to allow for an event to be dispatched (measured since its eventTime)
113// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000114constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115
Michael Wrightd02c5b62014-02-10 15:10:22 -0800116// 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 +0000117constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
118
119// Log a warning when an interception call takes longer than this to process.
120constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800121
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700122// Additional key latency in case a connection is still processing some motion events.
123// This will help with the case when a user touched a button that opens a new window,
124// and gives us the chance to dispatch the key to this new window.
125constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
126
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000128constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
129
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000130// Event log tags. See EventLogTags.logtags for reference
131constexpr int LOGTAG_INPUT_INTERACTION = 62000;
132constexpr int LOGTAG_INPUT_FOCUS = 62001;
133
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134static inline nsecs_t now() {
135 return systemTime(SYSTEM_TIME_MONOTONIC);
136}
137
138static inline const char* toString(bool value) {
139 return value ? "true" : "false";
140}
141
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000142static inline const std::string toString(sp<IBinder> binder) {
143 if (binder == nullptr) {
144 return "<null>";
145 }
146 return StringPrintf("%p", binder.get());
147}
148
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700150 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
151 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152}
153
154static bool isValidKeyAction(int32_t action) {
155 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AKEY_EVENT_ACTION_DOWN:
157 case AKEY_EVENT_ACTION_UP:
158 return true;
159 default:
160 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161 }
162}
163
164static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 ALOGE("Key event has invalid action code 0x%x", action);
167 return false;
168 }
169 return true;
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_DOWN:
175 case AMOTION_EVENT_ACTION_UP:
176 case AMOTION_EVENT_ACTION_CANCEL:
177 case AMOTION_EVENT_ACTION_MOVE:
178 case AMOTION_EVENT_ACTION_OUTSIDE:
179 case AMOTION_EVENT_ACTION_HOVER_ENTER:
180 case AMOTION_EVENT_ACTION_HOVER_MOVE:
181 case AMOTION_EVENT_ACTION_HOVER_EXIT:
182 case AMOTION_EVENT_ACTION_SCROLL:
183 return true;
184 case AMOTION_EVENT_ACTION_POINTER_DOWN:
185 case AMOTION_EVENT_ACTION_POINTER_UP: {
186 int32_t index = getMotionEventActionPointerIndex(action);
187 return index >= 0 && index < pointerCount;
188 }
189 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
190 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
191 return actionButton != 0;
192 default:
193 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 }
195}
196
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500197static int64_t millis(std::chrono::nanoseconds t) {
198 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
199}
200
Michael Wright7b159c92015-05-14 14:48:03 +0100201static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 const PointerProperties* pointerProperties) {
203 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 ALOGE("Motion event has invalid action code 0x%x", action);
205 return false;
206 }
207 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000208 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700209 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 return false;
211 }
212 BitSet32 pointerIdBits;
213 for (size_t i = 0; i < pointerCount; i++) {
214 int32_t id = pointerProperties[i].id;
215 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700216 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
217 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 return false;
219 }
220 if (pointerIdBits.hasBit(id)) {
221 ALOGE("Motion event has duplicate pointer id %d", id);
222 return false;
223 }
224 pointerIdBits.markBit(id);
225 }
226 return true;
227}
228
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000229static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000231 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
233
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000234 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 bool first = true;
236 Region::const_iterator cur = region.begin();
237 Region::const_iterator const tail = region.end();
238 while (cur != tail) {
239 if (first) {
240 first = false;
241 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800242 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800243 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800244 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245 cur++;
246 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000247 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248}
249
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500250static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
251 constexpr size_t maxEntries = 50; // max events to print
252 constexpr size_t skipBegin = maxEntries / 2;
253 const size_t skipEnd = queue.size() - maxEntries / 2;
254 // skip from maxEntries / 2 ... size() - maxEntries/2
255 // only print from 0 .. skipBegin and then from skipEnd .. size()
256
257 std::string dump;
258 for (size_t i = 0; i < queue.size(); i++) {
259 const DispatchEntry& entry = *queue[i];
260 if (i >= skipBegin && i < skipEnd) {
261 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
262 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
263 continue;
264 }
265 dump.append(INDENT4);
266 dump += entry.eventEntry->getDescription();
267 dump += StringPrintf(", seq=%" PRIu32
268 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
269 entry.seq, entry.targetFlags, entry.resolvedAction,
270 ns2ms(currentTime - entry.eventEntry->eventTime));
271 if (entry.deliveryTime != 0) {
272 // This entry was delivered, so add information on how long we've been waiting
273 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
274 }
275 dump.append("\n");
276 }
277 return dump;
278}
279
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700280/**
281 * Find the entry in std::unordered_map by key, and return it.
282 * If the entry is not found, return a default constructed entry.
283 *
284 * Useful when the entries are vectors, since an empty vector will be returned
285 * if the entry is not found.
286 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
287 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700288template <typename K, typename V>
289static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700290 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700291 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800292}
293
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700294/**
295 * Find the entry in std::unordered_map by value, and remove it.
296 * If more than one entry has the same value, then all matching
297 * key-value pairs will be removed.
298 *
299 * Return true if at least one value has been removed.
300 */
301template <typename K, typename V>
302static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
303 bool removed = false;
304 for (auto it = map.begin(); it != map.end();) {
305 if (it->second == value) {
306 it = map.erase(it);
307 removed = true;
308 } else {
309 it++;
310 }
311 }
312 return removed;
313}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800314
chaviwaf87b3e2019-10-01 16:59:28 -0700315static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
316 if (first == second) {
317 return true;
318 }
319
320 if (first == nullptr || second == nullptr) {
321 return false;
322 }
323
324 return first->getToken() == second->getToken();
325}
326
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000327static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
328 if (first == nullptr || second == nullptr) {
329 return false;
330 }
331 return first->applicationInfo.token != nullptr &&
332 first->applicationInfo.token == second->applicationInfo.token;
333}
334
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800335static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
336 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
337}
338
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000339static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700340 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000341 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900342 if (eventEntry->type == EventEntry::Type::MOTION) {
343 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800344 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900345 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800346 // Use identity transform for events that are not pointer events because their axes
347 // values do not represent on-screen coordinates, so they should not have any window
348 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900349 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
350 1.0f /*globalScaleFactor*/);
351 }
352 }
353
chaviw1ff3d1e2020-07-01 15:53:47 -0700354 if (inputTarget.useDefaultPointerTransform()) {
355 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700356 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358 }
359
360 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
361 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700363 std::vector<PointerCoords> pointerCoords;
364 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 // Use the first pointer information to normalize all other pointers. This could be any pointer
367 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700368 // uses the transform for the normalized pointer.
369 const ui::Transform& firstPointerTransform =
370 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
371 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 // Iterate through all pointers in the event to normalize against the first.
374 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
375 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
376 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700377 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378
379 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700380 // First, apply the current pointer's transform to update the coordinates into
381 // window space.
382 pointerCoords[pointerIndex].transform(currTransform);
383 // Next, apply the inverse transform of the normalized coordinates so the
384 // current coordinates are transformed into the normalized coordinate space.
385 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000386 }
387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700388 std::unique_ptr<MotionEntry> combinedMotionEntry =
389 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
390 motionEntry.deviceId, motionEntry.source,
391 motionEntry.displayId, motionEntry.policyFlags,
392 motionEntry.action, motionEntry.actionButton,
393 motionEntry.flags, motionEntry.metaState,
394 motionEntry.buttonState, motionEntry.classification,
395 motionEntry.edgeFlags, motionEntry.xPrecision,
396 motionEntry.yPrecision, motionEntry.xCursorPosition,
397 motionEntry.yCursorPosition, motionEntry.downTime,
398 motionEntry.pointerCount, motionEntry.pointerProperties,
399 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000400
401 if (motionEntry.injectionState) {
402 combinedMotionEntry->injectionState = motionEntry.injectionState;
403 combinedMotionEntry->injectionState->refCount += 1;
404 }
405
406 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700407 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
408 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000409 return dispatchEntry;
410}
411
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700412static void addGestureMonitors(const std::vector<Monitor>& monitors,
413 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
414 float yOffset = 0) {
415 if (monitors.empty()) {
416 return;
417 }
418 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
419 for (const Monitor& monitor : monitors) {
420 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
421 }
422}
423
Garfield Tan15601662020-09-22 15:32:38 -0700424static status_t openInputChannelPair(const std::string& name,
425 std::shared_ptr<InputChannel>& serverChannel,
426 std::unique_ptr<InputChannel>& clientChannel) {
427 std::unique_ptr<InputChannel> uniqueServerChannel;
428 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
429
430 serverChannel = std::move(uniqueServerChannel);
431 return result;
432}
433
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500434template <typename T>
435static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
436 if (lhs == nullptr && rhs == nullptr) {
437 return true;
438 }
439 if (lhs == nullptr || rhs == nullptr) {
440 return false;
441 }
442 return *lhs == *rhs;
443}
444
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000445static sp<IPlatformCompatNative> getCompatService() {
446 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
447 if (service == nullptr) {
448 ALOGE("Failed to link to compat service");
449 return nullptr;
450 }
451 return interface_cast<IPlatformCompatNative>(service);
452}
453
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000454static KeyEvent createKeyEvent(const KeyEntry& entry) {
455 KeyEvent event;
456 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
457 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
458 entry.repeatCount, entry.downTime, entry.eventTime);
459 return event;
460}
461
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000462static std::optional<int32_t> findMonitorPidByToken(
463 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
464 const sp<IBinder>& token) {
465 for (const auto& it : monitorsByDisplay) {
466 const std::vector<Monitor>& monitors = it.second;
467 for (const Monitor& monitor : monitors) {
468 if (monitor.inputChannel->getConnectionToken() == token) {
469 return monitor.pid;
470 }
471 }
472 }
473 return std::nullopt;
474}
475
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476// --- InputDispatcher ---
477
Garfield Tan00f511d2019-06-12 16:55:40 -0700478InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
479 : mPolicy(policy),
480 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700481 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800482 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700483 mAppSwitchSawKeyDown(false),
484 mAppSwitchDueTime(LONG_LONG_MAX),
485 mNextUnblockedEvent(nullptr),
486 mDispatchEnabled(false),
487 mDispatchFrozen(false),
488 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800489 // mInTouchMode will be initialized by the WindowManager to the default device config.
490 // To avoid leaking stack in case that call never comes, and for tests,
491 // initialize it here anyways.
492 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100493 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000494 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800495 mFocusedWindowRequestedPointerCapture(false),
496 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000497 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800499 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500
Yi Kong9b14ac62018-07-17 13:48:38 -0700501 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502
503 policy->getDispatcherConfiguration(&mConfig);
504}
505
506InputDispatcher::~InputDispatcher() {
507 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800508 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509
510 resetKeyRepeatLocked();
511 releasePendingEventLocked();
512 drainInboundQueueLocked();
513 }
514
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700515 while (!mConnectionsByFd.empty()) {
516 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700517 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 }
519}
520
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700521status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700522 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700523 return ALREADY_EXISTS;
524 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700525 mThread = std::make_unique<InputThread>(
526 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
527 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700528}
529
530status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700531 if (mThread && mThread->isCallingThread()) {
532 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700533 return INVALID_OPERATION;
534 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700535 mThread.reset();
536 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700537}
538
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539void InputDispatcher::dispatchOnce() {
540 nsecs_t nextWakeupTime = LONG_LONG_MAX;
541 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800542 std::scoped_lock _l(mLock);
543 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544
545 // Run a dispatch loop if there are no pending commands.
546 // The dispatch loop might enqueue commands to run afterwards.
547 if (!haveCommandsLocked()) {
548 dispatchOnceInnerLocked(&nextWakeupTime);
549 }
550
551 // Run all pending commands if there are any.
552 // If any commands were run then force the next poll to wake up immediately.
553 if (runCommandsLockedInterruptible()) {
554 nextWakeupTime = LONG_LONG_MIN;
555 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800556
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700557 // If we are still waiting for ack on some events,
558 // we might have to wake up earlier to check if an app is anr'ing.
559 const nsecs_t nextAnrCheck = processAnrsLocked();
560 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
561
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800562 // We are about to enter an infinitely long sleep, because we have no commands or
563 // pending or queued events
564 if (nextWakeupTime == LONG_LONG_MAX) {
565 mDispatcherEnteredIdle.notify_all();
566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 } // release lock
568
569 // Wait for callback or timeout or wake. (make sure we round up, not down)
570 nsecs_t currentTime = now();
571 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
572 mLooper->pollOnce(timeoutMillis);
573}
574
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700575/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500576 * Raise ANR if there is no focused window.
577 * Before the ANR is raised, do a final state check:
578 * 1. The currently focused application must be the same one we are waiting for.
579 * 2. Ensure we still don't have a focused window.
580 */
581void InputDispatcher::processNoFocusedWindowAnrLocked() {
582 // Check if the application that we are waiting for is still focused.
583 std::shared_ptr<InputApplicationHandle> focusedApplication =
584 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
585 if (focusedApplication == nullptr ||
586 focusedApplication->getApplicationToken() !=
587 mAwaitedFocusedApplication->getApplicationToken()) {
588 // Unexpected because we should have reset the ANR timer when focused application changed
589 ALOGE("Waited for a focused window, but focused application has already changed to %s",
590 focusedApplication->getName().c_str());
591 return; // The focused application has changed.
592 }
593
594 const sp<InputWindowHandle>& focusedWindowHandle =
595 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
596 if (focusedWindowHandle != nullptr) {
597 return; // We now have a focused window. No need for ANR.
598 }
599 onAnrLocked(mAwaitedFocusedApplication);
600}
601
602/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700603 * Check if any of the connections' wait queues have events that are too old.
604 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
605 * Return the time at which we should wake up next.
606 */
607nsecs_t InputDispatcher::processAnrsLocked() {
608 const nsecs_t currentTime = now();
609 nsecs_t nextAnrCheck = LONG_LONG_MAX;
610 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
611 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
612 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500613 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700614 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500615 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700616 return LONG_LONG_MIN;
617 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500618 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700619 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
620 }
621 }
622
623 // Check if any connection ANRs are due
624 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
625 if (currentTime < nextAnrCheck) { // most likely scenario
626 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
627 }
628
629 // If we reached here, we have an unresponsive connection.
630 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
631 if (connection == nullptr) {
632 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
633 return nextAnrCheck;
634 }
635 connection->responsive = false;
636 // Stop waking up for this unresponsive connection
637 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000638 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700639 return LONG_LONG_MIN;
640}
641
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500642std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700643 sp<InputWindowHandle> window = getWindowHandleLocked(token);
644 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500645 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700646 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500647 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700648}
649
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
651 nsecs_t currentTime = now();
652
Jeff Browndc5992e2014-04-11 01:27:26 -0700653 // Reset the key repeat timer whenever normal dispatch is suspended while the
654 // device is in a non-interactive state. This is to ensure that we abort a key
655 // repeat if the device is just coming out of sleep.
656 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 resetKeyRepeatLocked();
658 }
659
660 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
661 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100662 if (DEBUG_FOCUS) {
663 ALOGD("Dispatch frozen. Waiting some more.");
664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 return;
666 }
667
668 // Optimize latency of app switches.
669 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
670 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
671 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
672 if (mAppSwitchDueTime < *nextWakeupTime) {
673 *nextWakeupTime = mAppSwitchDueTime;
674 }
675
676 // Ready to start a new event.
677 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700678 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700679 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 if (isAppSwitchDue) {
681 // The inbound queue is empty so the app switch key we were waiting
682 // for will never arrive. Stop waiting for it.
683 resetPendingAppSwitchLocked(false);
684 isAppSwitchDue = false;
685 }
686
687 // Synthesize a key repeat if appropriate.
688 if (mKeyRepeatState.lastKeyEntry) {
689 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
690 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
691 } else {
692 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
693 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
694 }
695 }
696 }
697
698 // Nothing to do if there is no pending event.
699 if (!mPendingEvent) {
700 return;
701 }
702 } else {
703 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700704 mPendingEvent = mInboundQueue.front();
705 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 traceInboundQueueLengthLocked();
707 }
708
709 // Poke user activity for this event.
710 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700711 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 }
714
715 // Now we have an event to dispatch.
716 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700717 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700719 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700721 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700723 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 }
725
726 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700727 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 }
729
730 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700731 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700732 const ConfigurationChangedEntry& typedEntry =
733 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700734 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700735 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700736 break;
737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700739 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700740 const DeviceResetEntry& typedEntry =
741 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700743 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700744 break;
745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100747 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700748 std::shared_ptr<FocusEntry> typedEntry =
749 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100750 dispatchFocusLocked(currentTime, typedEntry);
751 done = true;
752 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
753 break;
754 }
755
Prabir Pradhan99987712020-11-10 18:43:05 -0800756 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
757 const auto typedEntry =
758 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
759 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
760 done = true;
761 break;
762 }
763
arthurhungb89ccb02020-12-30 16:19:01 +0800764 case EventEntry::Type::DRAG: {
765 std::shared_ptr<DragEntry> typedEntry =
766 std::static_pointer_cast<DragEntry>(mPendingEvent);
767 dispatchDragLocked(currentTime, typedEntry);
768 done = true;
769 break;
770 }
771
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700773 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700775 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700776 resetPendingAppSwitchLocked(true);
777 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 } else if (dropReason == DropReason::NOT_DROPPED) {
779 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 }
781 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700782 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700784 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700785 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
786 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700788 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 break;
790 }
791
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700792 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700793 std::shared_ptr<MotionEntry> motionEntry =
794 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700795 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
796 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700798 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700799 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700800 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700801 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
802 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700804 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
Chris Yef59a2f42020-10-16 12:55:26 -0700807
808 case EventEntry::Type::SENSOR: {
809 std::shared_ptr<SensorEntry> sensorEntry =
810 std::static_pointer_cast<SensorEntry>(mPendingEvent);
811 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
812 dropReason = DropReason::APP_SWITCH;
813 }
814 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
815 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
816 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
817 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
818 dropReason = DropReason::STALE;
819 }
820 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
821 done = true;
822 break;
823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
825
826 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700827 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700828 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 }
Michael Wright3a981722015-06-10 15:26:13 +0100830 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831
832 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834 }
835}
836
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700837/**
838 * Return true if the events preceding this incoming motion event should be dropped
839 * Return false otherwise (the default behaviour)
840 */
841bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700842 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700843 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700844
845 // Optimize case where the current application is unresponsive and the user
846 // decides to touch a window in a different application.
847 // If the application takes too long to catch up then we drop all events preceding
848 // the touch into the other window.
849 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700850 int32_t displayId = motionEntry.displayId;
851 int32_t x = static_cast<int32_t>(
852 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
853 int32_t y = static_cast<int32_t>(
854 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
855 sp<InputWindowHandle> touchedWindowHandle =
856 findTouchedWindowAtLocked(displayId, x, y, nullptr);
857 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700858 touchedWindowHandle->getApplicationToken() !=
859 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700860 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700861 ALOGI("Pruning input queue because user touched a different application while waiting "
862 "for %s",
863 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700864 return true;
865 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700866
867 // Alternatively, maybe there's a gesture monitor that could handle this event
868 std::vector<TouchedMonitor> gestureMonitors =
869 findTouchedGestureMonitorsLocked(displayId, {});
870 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
871 sp<Connection> connection =
872 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000873 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700874 // This monitor could take more input. Drop all events preceding this
875 // event, so that gesture monitor could get a chance to receive the stream
876 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
877 "responsive gesture monitor that may handle the event",
878 mAwaitedFocusedApplication->getName().c_str());
879 return true;
880 }
881 }
882 }
883
884 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
885 // yet been processed by some connections, the dispatcher will wait for these motion
886 // events to be processed before dispatching the key event. This is because these motion events
887 // may cause a new window to be launched, which the user might expect to receive focus.
888 // To prevent waiting forever for such events, just send the key to the currently focused window
889 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
890 ALOGD("Received a new pointer down event, stop waiting for events to process and "
891 "just send the pending key event to the focused window.");
892 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700893 }
894 return false;
895}
896
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700897bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700898 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700899 mInboundQueue.push_back(std::move(newEntry));
900 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 traceInboundQueueLengthLocked();
902
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700903 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700904 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 // Optimize app switch latency.
906 // If the application takes too long to catch up then we drop all events preceding
907 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700908 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700910 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700911 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700912 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700917 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 mAppSwitchSawKeyDown = false;
919 needWake = true;
920 }
921 }
922 }
923 break;
924 }
925
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700926 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700927 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
928 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100933 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700934 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
935 break;
936 }
937 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800938 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700939 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800940 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
941 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700942 // nothing to do
943 break;
944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 }
946
947 return needWake;
948}
949
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700950void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700951 // Do not store sensor event in recent queue to avoid flooding the queue.
952 if (entry->type != EventEntry::Type::SENSOR) {
953 mRecentQueue.push_back(entry);
954 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700955 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700956 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
958}
959
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700961 int32_t y, TouchState* touchState,
962 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800963 bool addPortalWindows,
964 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700965 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
966 LOG_ALWAYS_FATAL(
967 "Must provide a valid touch state if adding portal windows or outside targets");
968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700970 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800971 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +0800972 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +0800973 continue;
974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 const InputWindowInfo* windowInfo = windowHandle->getInfo();
976 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100977 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978
979 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100980 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
981 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
982 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800984 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 if (portalToDisplayId != ADISPLAY_ID_NONE &&
986 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800987 if (addPortalWindows) {
988 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700989 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800990 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700991 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 // Found window.
995 return windowHandle;
996 }
997 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800998
Michael Wright44753b12020-07-08 13:48:11 +0100999 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001000 touchState->addOrUpdateWindow(windowHandle,
1001 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1002 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 }
1006 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001007 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008}
1009
Garfield Tane84e6f92019-08-29 17:28:41 -07001010std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001011 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001012 std::vector<TouchedMonitor> touchedMonitors;
1013
1014 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1015 addGestureMonitors(monitors, touchedMonitors);
1016 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1017 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1018 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1020 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001021 }
1022 return touchedMonitors;
1023}
1024
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001025void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 const char* reason;
1027 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 reason = "inbound event was dropped because the policy consumed it";
1033 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001034 case DropReason::DISABLED:
1035 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036 ALOGI("Dropped event because input dispatch is disabled.");
1037 }
1038 reason = "inbound event was dropped because input dispatch is disabled";
1039 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001040 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001041 ALOGI("Dropped event because of pending overdue app switch.");
1042 reason = "inbound event was dropped because of pending overdue app switch";
1043 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001044 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 ALOGI("Dropped event because the current application is not responding and the user "
1046 "has started interacting with a different application.");
1047 reason = "inbound event was dropped because the current application is not responding "
1048 "and the user has started interacting with a different application";
1049 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 ALOGI("Dropped event because it is stale.");
1052 reason = "inbound event was dropped because it is stale";
1053 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001054 case DropReason::NO_POINTER_CAPTURE:
1055 ALOGI("Dropped event because there is no window with Pointer Capture.");
1056 reason = "inbound event was dropped because there is no window with Pointer Capture";
1057 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001058 case DropReason::NOT_DROPPED: {
1059 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 }
1063
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001064 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1067 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001070 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001071 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1072 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1074 synthesizeCancelationEventsForAllConnectionsLocked(options);
1075 } else {
1076 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1077 synthesizeCancelationEventsForAllConnectionsLocked(options);
1078 }
1079 break;
1080 }
Chris Yef59a2f42020-10-16 12:55:26 -07001081 case EventEntry::Type::SENSOR: {
1082 break;
1083 }
arthurhungb89ccb02020-12-30 16:19:01 +08001084 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1085 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001086 break;
1087 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001088 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001089 case EventEntry::Type::CONFIGURATION_CHANGED:
1090 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001091 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001092 break;
1093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095}
1096
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001097static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1099 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100}
1101
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1103 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1104 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1105 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106}
1107
1108bool InputDispatcher::isAppSwitchPendingLocked() {
1109 return mAppSwitchDueTime != LONG_LONG_MAX;
1110}
1111
1112void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1113 mAppSwitchDueTime = LONG_LONG_MAX;
1114
1115#if DEBUG_APP_SWITCH
1116 if (handled) {
1117 ALOGD("App switch has arrived.");
1118 } else {
1119 ALOGD("App switch was abandoned.");
1120 }
1121#endif
1122}
1123
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001125 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126}
1127
1128bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001129 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 return false;
1131 }
1132
1133 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001134 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001135 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001137 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138
1139 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001140 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 return true;
1142}
1143
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001144void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1145 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146}
1147
1148void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001149 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001151 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 releaseInboundEventLocked(entry);
1153 }
1154 traceInboundQueueLengthLocked();
1155}
1156
1157void InputDispatcher::releasePendingEventLocked() {
1158 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001160 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 }
1162}
1163
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001164void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001166 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167#if DEBUG_DISPATCH_CYCLE
1168 ALOGD("Injected inbound event was dropped.");
1169#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001170 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 }
1172 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001173 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176}
1177
1178void InputDispatcher::resetKeyRepeatLocked() {
1179 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001180 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182}
1183
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001184std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1185 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186
Michael Wright2e732952014-09-24 13:26:59 -07001187 uint32_t policyFlags = entry->policyFlags &
1188 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001190 std::shared_ptr<KeyEntry> newEntry =
1191 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1192 entry->source, entry->displayId, policyFlags, entry->action,
1193 entry->flags, entry->keyCode, entry->scanCode,
1194 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 newEntry->syntheticRepeat = true;
1197 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200}
1201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001205 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206#endif
1207
1208 // Reset key repeating in case a keyboard device was added or removed or something.
1209 resetKeyRepeatLocked();
1210
1211 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001212 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1213 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001214 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 return true;
1217}
1218
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001219bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1220 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1223 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224#endif
1225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001226 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001227 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 synthesizeCancelationEventsForAllConnectionsLocked(options);
1229 return true;
1230}
1231
Vishnu Nairad321cd2020-08-20 16:40:21 -07001232void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001233 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001234 if (mPendingEvent != nullptr) {
1235 // Move the pending event to the front of the queue. This will give the chance
1236 // for the pending event to get dispatched to the newly focused window
1237 mInboundQueue.push_front(mPendingEvent);
1238 mPendingEvent = nullptr;
1239 }
1240
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 std::unique_ptr<FocusEntry> focusEntry =
1242 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1243 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001244
1245 // This event should go to the front of the queue, but behind all other focus events
1246 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001248 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249 [](const std::shared_ptr<EventEntry>& event) {
1250 return event->type == EventEntry::Type::FOCUS;
1251 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001252
1253 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001255}
1256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001258 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001259 if (channel == nullptr) {
1260 return; // Window has gone away
1261 }
1262 InputTarget target;
1263 target.inputChannel = channel;
1264 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1265 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001266 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1267 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001268 std::string reason = std::string("reason=").append(entry->reason);
1269 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001270 dispatchEventLocked(currentTime, entry, {target});
1271}
1272
Prabir Pradhan99987712020-11-10 18:43:05 -08001273void InputDispatcher::dispatchPointerCaptureChangedLocked(
1274 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1275 DropReason& dropReason) {
1276 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001277 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1278 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1279 }
1280 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001281 // Pointer capture was already forcefully disabled because of focus change.
1282 dropReason = DropReason::NOT_DROPPED;
1283 return;
1284 }
1285
1286 // Set drop reason for early returns
1287 dropReason = DropReason::NO_POINTER_CAPTURE;
1288
1289 sp<IBinder> token;
1290 if (entry->pointerCaptureEnabled) {
1291 // Enable Pointer Capture
1292 if (!mFocusedWindowRequestedPointerCapture) {
1293 // This can happen if a window requests capture and immediately releases capture.
1294 ALOGW("No window requested Pointer Capture.");
1295 return;
1296 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001297 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001298 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1299 mWindowTokenWithPointerCapture = token;
1300 } else {
1301 // Disable Pointer Capture
1302 token = mWindowTokenWithPointerCapture;
1303 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001304 if (mFocusedWindowRequestedPointerCapture) {
1305 mFocusedWindowRequestedPointerCapture = false;
1306 setPointerCaptureLocked(false);
1307 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001308 }
1309
1310 auto channel = getInputChannelLocked(token);
1311 if (channel == nullptr) {
1312 // Window has gone away, clean up Pointer Capture state.
1313 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001314 if (mFocusedWindowRequestedPointerCapture) {
1315 mFocusedWindowRequestedPointerCapture = false;
1316 setPointerCaptureLocked(false);
1317 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001318 return;
1319 }
1320 InputTarget target;
1321 target.inputChannel = channel;
1322 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1323 entry->dispatchInProgress = true;
1324 dispatchEventLocked(currentTime, entry, {target});
1325
1326 dropReason = DropReason::NOT_DROPPED;
1327}
1328
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001329bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001332 if (!entry->dispatchInProgress) {
1333 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1334 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1335 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1336 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001337 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 // We have seen two identical key downs in a row which indicates that the device
1339 // driver is automatically generating key repeats itself. We take note of the
1340 // repeat here, but we disable our own next key repeat timer since it is clear that
1341 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001342 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1343 // Make sure we don't get key down from a different device. If a different
1344 // device Id has same key pressed down, the new device Id will replace the
1345 // current one to hold the key repeat with repeat count reset.
1346 // In the future when got a KEY_UP on the device id, drop it and do not
1347 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1349 resetKeyRepeatLocked();
1350 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1351 } else {
1352 // Not a repeat. Save key down state in case we do see a repeat later.
1353 resetKeyRepeatLocked();
1354 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1355 }
1356 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001357 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1358 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001359 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001360#if DEBUG_INBOUND_EVENT_DETAILS
1361 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1362#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001363 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 resetKeyRepeatLocked();
1365 }
1366
1367 if (entry->repeatCount == 1) {
1368 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1369 } else {
1370 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1371 }
1372
1373 entry->dispatchInProgress = true;
1374
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001375 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
1377
1378 // Handle case where the policy asked us to try again later last time.
1379 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1380 if (currentTime < entry->interceptKeyWakeupTime) {
1381 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1382 *nextWakeupTime = entry->interceptKeyWakeupTime;
1383 }
1384 return false; // wait until next wakeup
1385 }
1386 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1387 entry->interceptKeyWakeupTime = 0;
1388 }
1389
1390 // Give the policy a chance to intercept the key.
1391 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1392 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001393 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001394 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001395 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001396 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001397 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001399 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 return false; // wait for the command to run
1401 } else {
1402 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1403 }
1404 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001405 if (*dropReason == DropReason::NOT_DROPPED) {
1406 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 }
1408 }
1409
1410 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001411 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001412 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001413 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1414 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001415 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 return true;
1417 }
1418
1419 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001420 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001421 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001422 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001423 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 return false;
1425 }
1426
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001427 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 return true;
1430 }
1431
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001432 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001433 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434
1435 // Dispatch the key.
1436 dispatchEventLocked(currentTime, entry, inputTargets);
1437 return true;
1438}
1439
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001440void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001442 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1444 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001445 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1446 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1447 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448#endif
1449}
1450
Chris Yef59a2f42020-10-16 12:55:26 -07001451void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1452 mLock.unlock();
1453
1454 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1455 if (entry->accuracyChanged) {
1456 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1457 }
1458 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1459 entry->hwTimestamp, entry->values);
1460 mLock.lock();
1461}
1462
1463void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1464 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1465#if DEBUG_OUTBOUND_EVENT_DETAILS
1466 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1467 "source=0x%x, sensorType=%s",
1468 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001469 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001470#endif
1471 std::unique_ptr<CommandEntry> commandEntry =
1472 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1473 commandEntry->sensorEntry = entry;
1474 postCommandLocked(std::move(commandEntry));
1475}
1476
1477bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1478#if DEBUG_OUTBOUND_EVENT_DETAILS
1479 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1480 NamedEnum::string(sensorType).c_str());
1481#endif
1482 { // acquire lock
1483 std::scoped_lock _l(mLock);
1484
1485 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1486 std::shared_ptr<EventEntry> entry = *it;
1487 if (entry->type == EventEntry::Type::SENSOR) {
1488 it = mInboundQueue.erase(it);
1489 releaseInboundEventLocked(entry);
1490 }
1491 }
1492 }
1493 return true;
1494}
1495
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001496bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001497 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001498 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001500 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 entry->dispatchInProgress = true;
1502
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001503 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 }
1505
1506 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001507 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001508 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001509 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1510 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 return true;
1512 }
1513
1514 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1515
1516 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001517 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518
1519 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001520 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 if (isPointerEvent) {
1522 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001523 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001524 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001525 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 } else {
1527 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001528 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001529 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001531 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return false;
1533 }
1534
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001535 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001536 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001537 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1538 return true;
1539 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001540 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001541 CancelationOptions::Mode mode(isPointerEvent
1542 ? CancelationOptions::CANCEL_POINTER_EVENTS
1543 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1544 CancelationOptions options(mode, "input event injection failed");
1545 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 return true;
1547 }
1548
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001549 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001550 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001552 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001553 std::unordered_map<int32_t, TouchState>::iterator it =
1554 mTouchStatesByDisplay.find(entry->displayId);
1555 if (it != mTouchStatesByDisplay.end()) {
1556 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001557 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001558 // The event has gone through these portal windows, so we add monitoring targets of
1559 // the corresponding displays as well.
1560 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001561 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001562 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001564 }
1565 }
1566 }
1567 }
1568
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 // Dispatch the motion.
1570 if (conflictingPointerActions) {
1571 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001572 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 synthesizeCancelationEventsForAllConnectionsLocked(options);
1574 }
1575 dispatchEventLocked(currentTime, entry, inputTargets);
1576 return true;
1577}
1578
arthurhungb89ccb02020-12-30 16:19:01 +08001579void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1580 bool isExiting, const MotionEntry& motionEntry) {
1581 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1582 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1583 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1584 PointerCoords pointerCoords;
1585 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1586 pointerCoords.transform(windowHandle->getInfo()->transform);
1587
1588 std::unique_ptr<DragEntry> dragEntry =
1589 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1590 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1591 pointerCoords.getY());
1592
1593 enqueueInboundEventLocked(std::move(dragEntry));
1594}
1595
1596void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1597 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1598 if (channel == nullptr) {
1599 return; // Window has gone away
1600 }
1601 InputTarget target;
1602 target.inputChannel = channel;
1603 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1604 entry->dispatchInProgress = true;
1605 dispatchEventLocked(currentTime, entry, {target});
1606}
1607
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001610 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 ", policyFlags=0x%x, "
1612 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1613 "metaState=0x%x, buttonState=0x%x,"
1614 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001615 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1616 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1617 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001619 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001621 "x=%f, y=%f, pressure=%f, size=%f, "
1622 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1623 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001624 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1625 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1626 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1627 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1628 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1629 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1630 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1631 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1632 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1633 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 }
1635#endif
1636}
1637
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001638void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1639 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001640 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001641 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642#if DEBUG_DISPATCH_CYCLE
1643 ALOGD("dispatchEventToCurrentInputTargets");
1644#endif
1645
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001646 updateInteractionTokensLocked(*eventEntry, inputTargets);
1647
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1649
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001652 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001653 sp<Connection> connection =
1654 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001655 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001656 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001658 if (DEBUG_FOCUS) {
1659 ALOGD("Dropping event delivery to target with channel '%s' because it "
1660 "is no longer registered with the input dispatcher.",
1661 inputTarget.inputChannel->getName().c_str());
1662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 }
1664 }
1665}
1666
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001667void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1668 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1669 // If the policy decides to close the app, we will get a channel removal event via
1670 // unregisterInputChannel, and will clean up the connection that way. We are already not
1671 // sending new pointers to the connection when it blocked, but focused events will continue to
1672 // pile up.
1673 ALOGW("Canceling events for %s because it is unresponsive",
1674 connection->inputChannel->getName().c_str());
1675 if (connection->status == Connection::STATUS_NORMAL) {
1676 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1677 "application not responding");
1678 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 }
1680}
1681
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001682void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001683 if (DEBUG_FOCUS) {
1684 ALOGD("Resetting ANR timeouts.");
1685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686
1687 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001688 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001689 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690}
1691
Tiger Huang721e26f2018-07-24 22:26:19 +08001692/**
1693 * Get the display id that the given event should go to. If this event specifies a valid display id,
1694 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1695 * Focused display is the display that the user most recently interacted with.
1696 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001697int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001698 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001699 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001700 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1702 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001703 break;
1704 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001705 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001706 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1707 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001708 break;
1709 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001710 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001711 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001712 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001713 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001714 case EventEntry::Type::SENSOR:
1715 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001716 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001717 return ADISPLAY_ID_NONE;
1718 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001719 }
1720 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1721}
1722
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001723bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1724 const char* focusedWindowName) {
1725 if (mAnrTracker.empty()) {
1726 // already processed all events that we waited for
1727 mKeyIsWaitingForEventsTimeout = std::nullopt;
1728 return false;
1729 }
1730
1731 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1732 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001733 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001734 mKeyIsWaitingForEventsTimeout = currentTime +
1735 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1736 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001737 return true;
1738 }
1739
1740 // We still have pending events, and already started the timer
1741 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1742 return true; // Still waiting
1743 }
1744
1745 // Waited too long, and some connection still hasn't processed all motions
1746 // Just send the key to the focused window
1747 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1748 focusedWindowName);
1749 mKeyIsWaitingForEventsTimeout = std::nullopt;
1750 return false;
1751}
1752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001753InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1754 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1755 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001756 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757
Tiger Huang721e26f2018-07-24 22:26:19 +08001758 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001759 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001760 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001761 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1762
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 // If there is no currently focused window and no focused application
1764 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001765 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1766 ALOGI("Dropping %s event because there is no focused window or focused application in "
1767 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001768 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001769 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 }
1771
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1773 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1774 // start interacting with another application via touch (app switch). This code can be removed
1775 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1776 // an app is expected to have a focused window.
1777 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1778 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1779 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001780 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1781 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1782 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001783 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001784 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001785 ALOGW("Waiting because no window has focus but %s may eventually add a "
1786 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001787 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001788 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001789 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001790 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1791 // Already raised ANR. Drop the event
1792 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001793 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001794 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001795 } else {
1796 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001797 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001798 }
1799 }
1800
1801 // we have a valid, non-null focused window
1802 resetNoFocusedWindowTimeoutLocked();
1803
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001805 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 }
1808
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001809 if (focusedWindowHandle->getInfo()->paused) {
1810 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001811 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001812 }
1813
1814 // If the event is a key event, then we must wait for all previous events to
1815 // complete before delivering it because previous events may have the
1816 // side-effect of transferring focus to a different window and we want to
1817 // ensure that the following keys are sent to the new window.
1818 //
1819 // Suppose the user touches a button in a window then immediately presses "A".
1820 // If the button causes a pop-up window to appear then we want to ensure that
1821 // the "A" key is delivered to the new pop-up window. This is because users
1822 // often anticipate pending UI changes when typing on a keyboard.
1823 // To obtain this behavior, we must serialize key events with respect to all
1824 // prior input events.
1825 if (entry.type == EventEntry::Type::KEY) {
1826 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1827 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001828 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 }
1831
1832 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001833 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001834 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1835 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836
1837 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001838 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839}
1840
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841/**
1842 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1843 * that are currently unresponsive.
1844 */
1845std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1846 const std::vector<TouchedMonitor>& monitors) const {
1847 std::vector<TouchedMonitor> responsiveMonitors;
1848 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1849 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1850 sp<Connection> connection = getConnectionLocked(
1851 monitor.monitor.inputChannel->getConnectionToken());
1852 if (connection == nullptr) {
1853 ALOGE("Could not find connection for monitor %s",
1854 monitor.monitor.inputChannel->getName().c_str());
1855 return false;
1856 }
1857 if (!connection->responsive) {
1858 ALOGW("Unresponsive monitor %s will not get the new gesture",
1859 connection->inputChannel->getName().c_str());
1860 return false;
1861 }
1862 return true;
1863 });
1864 return responsiveMonitors;
1865}
1866
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001867InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1868 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1869 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 enum InjectionPermission {
1872 INJECTION_PERMISSION_UNKNOWN,
1873 INJECTION_PERMISSION_GRANTED,
1874 INJECTION_PERMISSION_DENIED
1875 };
1876
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 // For security reasons, we defer updating the touch state until we are sure that
1878 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001879 int32_t displayId = entry.displayId;
1880 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1882
1883 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001886 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1887 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001889 // Copy current touch state into tempTouchState.
1890 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1891 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001892 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001893 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001894 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1895 mTouchStatesByDisplay.find(displayId);
1896 if (oldStateIt != mTouchStatesByDisplay.end()) {
1897 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001898 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001899 }
1900
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001901 bool isSplit = tempTouchState.split;
1902 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1903 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1904 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001905 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1906 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1907 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1908 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1909 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001910 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 bool wrongDevice = false;
1912 if (newGesture) {
1913 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001914 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001915 ALOGI("Dropping event because a pointer for a different device is already down "
1916 "in display %" PRId32,
1917 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001918 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001919 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 switchedDevice = false;
1921 wrongDevice = true;
1922 goto Failed;
1923 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001924 tempTouchState.reset();
1925 tempTouchState.down = down;
1926 tempTouchState.deviceId = entry.deviceId;
1927 tempTouchState.source = entry.source;
1928 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001930 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001931 ALOGI("Dropping move event because a pointer for a different device is already active "
1932 "in display %" PRId32,
1933 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001934 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001936 switchedDevice = false;
1937 wrongDevice = true;
1938 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 }
1940
1941 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1942 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1943
Garfield Tan00f511d2019-06-12 16:55:40 -07001944 int32_t x;
1945 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001947 // Always dispatch mouse events to cursor position.
1948 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001949 x = int32_t(entry.xCursorPosition);
1950 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001951 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001952 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1953 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001954 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001955 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001956 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001957 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1958 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001959
1960 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001961 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001962 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001965 if (newTouchedWindowHandle != nullptr &&
1966 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001967 // New window supports splitting, but we should never split mouse events.
1968 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 } else if (isSplit) {
1970 // New window does not support splitting but we have already split events.
1971 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001972 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 }
1974
1975 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001976 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001978 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001979 }
1980
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001981 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1982 ALOGI("Not sending touch event to %s because it is paused",
1983 newTouchedWindowHandle->getName().c_str());
1984 newTouchedWindowHandle = nullptr;
1985 }
1986
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001987 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001988 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001989 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1990 if (!isResponsive) {
1991 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001992 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1993 newTouchedWindowHandle = nullptr;
1994 }
1995 }
1996
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001997 // Drop events that can't be trusted due to occlusion
1998 if (newTouchedWindowHandle != nullptr &&
1999 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2000 TouchOcclusionInfo occlusionInfo =
2001 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002002 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002003 if (DEBUG_TOUCH_OCCLUSION) {
2004 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2005 for (const auto& log : occlusionInfo.debugInfo) {
2006 ALOGD("%s", log.c_str());
2007 }
2008 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002009 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2010 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2011 ALOGW("Dropping untrusted touch event due to %s/%d",
2012 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2013 newTouchedWindowHandle = nullptr;
2014 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002015 }
2016 }
2017
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002018 // Also don't send the new touch event to unresponsive gesture monitors
2019 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2020
Michael Wright3dd60e22019-03-27 22:06:44 +00002021 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2022 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002023 "(%d, %d) in display %" PRId32 ".",
2024 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002025 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002026 goto Failed;
2027 }
2028
2029 if (newTouchedWindowHandle != nullptr) {
2030 // Set target flags.
2031 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2032 if (isSplit) {
2033 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002035 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2036 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2037 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2038 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2039 }
2040
2041 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002042 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2043 newHoverWindowHandle = nullptr;
2044 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002045 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002046 }
2047
2048 // Update the temporary touch state.
2049 BitSet32 pointerIds;
2050 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002051 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002052 pointerIds.markBit(pointerId);
2053 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002054 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
2056
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002057 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 } else {
2059 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2060
2061 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002062 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002063 if (DEBUG_FOCUS) {
2064 ALOGD("Dropping event because the pointer is not down or we previously "
2065 "dropped the pointer down event in display %" PRId32,
2066 displayId);
2067 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002068 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 goto Failed;
2070 }
2071
arthurhung6d4bed92021-03-17 11:59:33 +08002072 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002073
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002075 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002076 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002077 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2078 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079
2080 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002081 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002082 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002083 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2084 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002085 if (DEBUG_FOCUS) {
2086 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2087 oldTouchedWindowHandle->getName().c_str(),
2088 newTouchedWindowHandle->getName().c_str(), displayId);
2089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002091 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2092 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2093 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094
2095 // Make a slippery entrance into the new window.
2096 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2097 isSplit = true;
2098 }
2099
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002100 int32_t targetFlags =
2101 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 if (isSplit) {
2103 targetFlags |= InputTarget::FLAG_SPLIT;
2104 }
2105 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2106 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002107 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2108 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 }
2110
2111 BitSet32 pointerIds;
2112 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002113 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002115 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
2117 }
2118 }
2119
2120 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002121 // Let the previous window know that the hover sequence is over, unless we already did it
2122 // when dispatching it as is to newTouchedWindowHandle.
2123 if (mLastHoverWindowHandle != nullptr &&
2124 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2125 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126#if DEBUG_HOVER
2127 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002128 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002130 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2131 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
2133
Garfield Tandf26e862020-07-01 20:18:19 -07002134 // Let the new window know that the hover sequence is starting, unless we already did it
2135 // when dispatching it as is to newTouchedWindowHandle.
2136 if (newHoverWindowHandle != nullptr &&
2137 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2138 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139#if DEBUG_HOVER
2140 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002143 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2144 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2145 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 }
2147 }
2148
2149 // Check permission to inject into all touched foreground windows and ensure there
2150 // is at least one touched foreground window.
2151 {
2152 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2155 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002156 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002157 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 injectionPermission = INJECTION_PERMISSION_DENIED;
2159 goto Failed;
2160 }
2161 }
2162 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002163 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002164 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002165 ALOGI("Dropping event because there is no touched foreground window in display "
2166 "%" PRId32 " or gesture monitor to receive it.",
2167 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002168 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 goto Failed;
2170 }
2171
2172 // Permission granted to injection into all touched foreground windows.
2173 injectionPermission = INJECTION_PERMISSION_GRANTED;
2174 }
2175
2176 // Check whether windows listening for outside touches are owned by the same UID. If it is
2177 // set the policy flag that we will not reveal coordinate information to this window.
2178 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2179 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002180 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002181 if (foregroundWindowHandle) {
2182 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002183 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002184 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2185 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2186 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002187 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2188 InputTarget::FLAG_ZERO_COORDS,
2189 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
2192 }
2193 }
2194 }
2195
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 // If this is the first pointer going down and the touched window has a wallpaper
2197 // then also add the touched wallpaper windows so they are locked in for the duration
2198 // of the touch gesture.
2199 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2200 // engine only supports touch events. We would need to add a mechanism similar
2201 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2202 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2203 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002205 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002206 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002207 getWindowHandlesLocked(displayId);
2208 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002210 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002211 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 .addOrUpdateWindow(windowHandle,
2214 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2215 InputTarget::
2216 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2217 InputTarget::FLAG_DISPATCH_AS_IS,
2218 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220 }
2221 }
2222 }
2223
2224 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002225 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002229 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002232 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002233 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002234 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002235 }
2236
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 // Drop the outside or hover touch windows since we will not care about them
2238 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002239 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240
2241Failed:
2242 // Check injection permission once and for all.
2243 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002244 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 injectionPermission = INJECTION_PERMISSION_GRANTED;
2246 } else {
2247 injectionPermission = INJECTION_PERMISSION_DENIED;
2248 }
2249 }
2250
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002251 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2252 return injectionResult;
2253 }
2254
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002256 if (!wrongDevice) {
2257 if (switchedDevice) {
2258 if (DEBUG_FOCUS) {
2259 ALOGD("Conflicting pointer actions: Switched to a different device.");
2260 }
2261 *outConflictingPointerActions = true;
2262 }
2263
2264 if (isHoverAction) {
2265 // Started hovering, therefore no longer down.
2266 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002267 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002268 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2269 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 *outConflictingPointerActions = true;
2272 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002273 tempTouchState.reset();
2274 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2275 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2276 tempTouchState.deviceId = entry.deviceId;
2277 tempTouchState.source = entry.source;
2278 tempTouchState.displayId = displayId;
2279 }
2280 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2281 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2282 // All pointers up or canceled.
2283 tempTouchState.reset();
2284 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2285 // First pointer went down.
2286 if (oldState && oldState->down) {
2287 if (DEBUG_FOCUS) {
2288 ALOGD("Conflicting pointer actions: Down received while already down.");
2289 }
2290 *outConflictingPointerActions = true;
2291 }
2292 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2293 // One pointer went up.
2294 if (isSplit) {
2295 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2296 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002298 for (size_t i = 0; i < tempTouchState.windows.size();) {
2299 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2300 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2301 touchedWindow.pointerIds.clearBit(pointerId);
2302 if (touchedWindow.pointerIds.isEmpty()) {
2303 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2304 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002307 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002309 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002310 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002311
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002312 // Save changes unless the action was scroll in which case the temporary touch
2313 // state was only valid for this one action.
2314 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2315 if (tempTouchState.displayId >= 0) {
2316 mTouchStatesByDisplay[displayId] = tempTouchState;
2317 } else {
2318 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002322 // Update hover state.
2323 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 return injectionResult;
2327}
2328
arthurhung6d4bed92021-03-17 11:59:33 +08002329void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2330 const sp<InputWindowHandle> dropWindow =
2331 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2332 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2333 true /*ignoreDragWindow*/);
2334 if (dropWindow) {
2335 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2336 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002337 } else {
2338 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002339 }
2340 mDragState.reset();
2341}
2342
2343void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2344 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002345 return;
2346 }
2347
arthurhung6d4bed92021-03-17 11:59:33 +08002348 if (!mDragState->isStartDrag) {
2349 mDragState->isStartDrag = true;
2350 mDragState->isStylusButtonDownAtStart =
2351 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2352 }
2353
arthurhungb89ccb02020-12-30 16:19:01 +08002354 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2355 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2356 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2357 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002358 // Handle the special case : stylus button no longer pressed.
2359 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2360 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2361 finishDragAndDrop(entry.displayId, x, y);
2362 return;
2363 }
2364
arthurhungb89ccb02020-12-30 16:19:01 +08002365 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002366 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002367 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2368 true /*ignoreDragWindow*/);
2369 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002370 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2371 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2372 if (mDragState->dragHoverWindowHandle != nullptr) {
2373 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2374 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002375 }
arthurhung6d4bed92021-03-17 11:59:33 +08002376 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002377 }
2378 // enqueue drag location if needed.
2379 if (hoverWindowHandle != nullptr) {
2380 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2381 }
arthurhung6d4bed92021-03-17 11:59:33 +08002382 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2383 finishDragAndDrop(entry.displayId, x, y);
2384 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002385 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002386 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002387 }
2388}
2389
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002391 int32_t targetFlags, BitSet32 pointerIds,
2392 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002393 std::vector<InputTarget>::iterator it =
2394 std::find_if(inputTargets.begin(), inputTargets.end(),
2395 [&windowHandle](const InputTarget& inputTarget) {
2396 return inputTarget.inputChannel->getConnectionToken() ==
2397 windowHandle->getToken();
2398 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002399
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002400 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002401
2402 if (it == inputTargets.end()) {
2403 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002404 std::shared_ptr<InputChannel> inputChannel =
2405 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002406 if (inputChannel == nullptr) {
2407 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2408 return;
2409 }
2410 inputTarget.inputChannel = inputChannel;
2411 inputTarget.flags = targetFlags;
2412 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2413 inputTargets.push_back(inputTarget);
2414 it = inputTargets.end() - 1;
2415 }
2416
2417 ALOG_ASSERT(it->flags == targetFlags);
2418 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2419
chaviw1ff3d1e2020-07-01 15:53:47 -07002420 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421}
2422
Michael Wright3dd60e22019-03-27 22:06:44 +00002423void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002424 int32_t displayId, float xOffset,
2425 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002426 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2427 mGlobalMonitorsByDisplay.find(displayId);
2428
2429 if (it != mGlobalMonitorsByDisplay.end()) {
2430 const std::vector<Monitor>& monitors = it->second;
2431 for (const Monitor& monitor : monitors) {
2432 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
2435}
2436
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002437void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2438 float yOffset,
2439 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002440 InputTarget target;
2441 target.inputChannel = monitor.inputChannel;
2442 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002443 ui::Transform t;
2444 t.set(xOffset, yOffset);
2445 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002446 inputTargets.push_back(target);
2447}
2448
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002450 const InjectionState* injectionState) {
2451 if (injectionState &&
2452 (windowHandle == nullptr ||
2453 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2454 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002455 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002457 "owned by uid %d",
2458 injectionState->injectorPid, injectionState->injectorUid,
2459 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 } else {
2461 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002462 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
2464 return false;
2465 }
2466 return true;
2467}
2468
Robert Carrc9bf1d32020-04-13 17:21:08 -07002469/**
2470 * Indicate whether one window handle should be considered as obscuring
2471 * another window handle. We only check a few preconditions. Actually
2472 * checking the bounds is left to the caller.
2473 */
2474static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2475 const sp<InputWindowHandle>& otherHandle) {
2476 // Compare by token so cloned layers aren't counted
2477 if (haveSameToken(windowHandle, otherHandle)) {
2478 return false;
2479 }
2480 auto info = windowHandle->getInfo();
2481 auto otherInfo = otherHandle->getInfo();
2482 if (!otherInfo->visible) {
2483 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002484 } else if (otherInfo->alpha == 0 &&
2485 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2486 // Those act as if they were invisible, so we don't need to flag them.
2487 // We do want to potentially flag touchable windows even if they have 0
2488 // opacity, since they can consume touches and alter the effects of the
2489 // user interaction (eg. apps that rely on
2490 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2491 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2492 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002493 } else if (info->ownerUid == otherInfo->ownerUid) {
2494 // If ownerUid is the same we don't generate occlusion events as there
2495 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002496 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002497 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002498 return false;
2499 } else if (otherInfo->displayId != info->displayId) {
2500 return false;
2501 }
2502 return true;
2503}
2504
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002505/**
2506 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2507 * untrusted, one should check:
2508 *
2509 * 1. If result.hasBlockingOcclusion is true.
2510 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2511 * BLOCK_UNTRUSTED.
2512 *
2513 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2514 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2515 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2516 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2517 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2518 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2519 *
2520 * If neither of those is true, then it means the touch can be allowed.
2521 */
2522InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2523 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002524 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2525 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002526 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2527 TouchOcclusionInfo info;
2528 info.hasBlockingOcclusion = false;
2529 info.obscuringOpacity = 0;
2530 info.obscuringUid = -1;
2531 std::map<int32_t, float> opacityByUid;
2532 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2533 if (windowHandle == otherHandle) {
2534 break; // All future windows are below us. Exit early.
2535 }
2536 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002537 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2538 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002539 if (DEBUG_TOUCH_OCCLUSION) {
2540 info.debugInfo.push_back(
2541 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2542 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002543 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2544 // we perform the checks below to see if the touch can be propagated or not based on the
2545 // window's touch occlusion mode
2546 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2547 info.hasBlockingOcclusion = true;
2548 info.obscuringUid = otherInfo->ownerUid;
2549 info.obscuringPackage = otherInfo->packageName;
2550 break;
2551 }
2552 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2553 uint32_t uid = otherInfo->ownerUid;
2554 float opacity =
2555 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2556 // Given windows A and B:
2557 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2558 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2559 opacityByUid[uid] = opacity;
2560 if (opacity > info.obscuringOpacity) {
2561 info.obscuringOpacity = opacity;
2562 info.obscuringUid = uid;
2563 info.obscuringPackage = otherInfo->packageName;
2564 }
2565 }
2566 }
2567 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002568 if (DEBUG_TOUCH_OCCLUSION) {
2569 info.debugInfo.push_back(
2570 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2571 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002572 return info;
2573}
2574
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002575std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2576 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002577 return StringPrintf(INDENT2
2578 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2579 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2580 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2581 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002582 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002583 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002584 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002585 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2586 info->frameTop, info->frameRight, info->frameBottom,
2587 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002588 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2589 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2590 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002591}
2592
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002593bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2594 if (occlusionInfo.hasBlockingOcclusion) {
2595 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2596 occlusionInfo.obscuringUid);
2597 return false;
2598 }
2599 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2600 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2601 "%.2f, maximum allowed = %.2f)",
2602 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2603 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2604 return false;
2605 }
2606 return true;
2607}
2608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002609bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2610 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002612 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002613 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002614 if (windowHandle == otherHandle) {
2615 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002618 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002619 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 return true;
2621 }
2622 }
2623 return false;
2624}
2625
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002626bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2627 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002628 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002629 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002630 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002631 if (windowHandle == otherHandle) {
2632 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002633 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002634 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002635 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002636 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002637 return true;
2638 }
2639 }
2640 return false;
2641}
2642
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002643std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002644 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002646 if (applicationHandle != nullptr) {
2647 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002648 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 } else {
2650 return applicationHandle->getName();
2651 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002652 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002653 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002655 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 }
2657}
2658
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002659void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002660 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002661 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2662 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002663 // Focus or pointer capture changed events are passed to apps, but do not represent user
2664 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002665 return;
2666 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002667 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002668 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002669 if (focusedWindowHandle != nullptr) {
2670 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002671 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002673 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674#endif
2675 return;
2676 }
2677 }
2678
2679 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002680 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002681 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002682 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2683 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002684 return;
2685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002687 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002688 eventType = USER_ACTIVITY_EVENT_TOUCH;
2689 }
2690 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002692 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002693 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2694 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002695 return;
2696 }
2697 eventType = USER_ACTIVITY_EVENT_BUTTON;
2698 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002700 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002701 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002702 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002703 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002704 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2705 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002706 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002707 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002708 break;
2709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 }
2711
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002712 std::unique_ptr<CommandEntry> commandEntry =
2713 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002714 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002716 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002717 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718}
2719
2720void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002722 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002723 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002724 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002726 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002727 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002728 ATRACE_NAME(message.c_str());
2729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730#if DEBUG_DISPATCH_CYCLE
2731 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002732 "globalScaleFactor=%f, pointerIds=0x%x %s",
2733 connection->getInputChannelName().c_str(), inputTarget.flags,
2734 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2735 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736#endif
2737
2738 // Skip this event if the connection status is not normal.
2739 // We don't want to enqueue additional outbound events if the connection is broken.
2740 if (connection->status != Connection::STATUS_NORMAL) {
2741#if DEBUG_DISPATCH_CYCLE
2742 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002743 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744#endif
2745 return;
2746 }
2747
2748 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002749 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2750 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2751 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002752 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002754 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002755 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002756 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002757 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 if (!splitMotionEntry) {
2759 return; // split event was dropped
2760 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002761 if (DEBUG_FOCUS) {
2762 ALOGD("channel '%s' ~ Split motion event.",
2763 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002764 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002765 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002766 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2767 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 return;
2769 }
2770 }
2771
2772 // Not splitting. Enqueue dispatch entries for the event as is.
2773 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2774}
2775
2776void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002778 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002779 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002780 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002782 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002783 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002784 ATRACE_NAME(message.c_str());
2785 }
2786
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002787 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788
2789 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002790 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002792 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002793 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002794 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002795 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002796 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002797 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002798 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002799 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002800 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802
2803 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002804 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 startDispatchCycleLocked(currentTime, connection);
2806 }
2807}
2808
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002809void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002810 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002811 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002813 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002814 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2815 connection->getInputChannelName().c_str(),
2816 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002817 ATRACE_NAME(message.c_str());
2818 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002819 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 if (!(inputTargetFlags & dispatchMode)) {
2821 return;
2822 }
2823 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2824
2825 // This is a new event.
2826 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002827 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002828 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002830 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2831 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002832 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002834 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002835 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002836 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002837 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002838 dispatchEntry->resolvedAction = keyEntry.action;
2839 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2842 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2845 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 return; // skip the inconsistent event
2848 }
2849 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002852 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002853 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002854 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2855 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2856 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2857 static_cast<int32_t>(IdGenerator::Source::OTHER);
2858 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002859 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2860 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2861 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2862 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2863 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2864 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2865 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2866 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2867 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2868 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2869 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002870 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002871 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002872 }
2873 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002874 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2875 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2878 "event",
2879 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2886 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2887 }
2888 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2889 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2893 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2896 "event",
2897 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 return; // skip the inconsistent event
2900 }
2901
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002902 dispatchEntry->resolvedEventId =
2903 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2904 ? mIdGenerator.nextId()
2905 : motionEntry.id;
2906 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2907 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2908 ") to MotionEvent(id=0x%" PRIx32 ").",
2909 motionEntry.id, dispatchEntry->resolvedEventId);
2910 ATRACE_NAME(message.c_str());
2911 }
2912
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002913 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002914 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915
2916 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002918 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002919 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2920 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002921 break;
2922 }
Chris Yef59a2f42020-10-16 12:55:26 -07002923 case EventEntry::Type::SENSOR: {
2924 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2925 break;
2926 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002927 case EventEntry::Type::CONFIGURATION_CHANGED:
2928 case EventEntry::Type::DEVICE_RESET: {
2929 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002930 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002931 break;
2932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
2934
2935 // Remember that we are waiting for this dispatch to complete.
2936 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002937 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 }
2939
2940 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002941 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002942 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002943}
2944
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002945/**
2946 * This function is purely for debugging. It helps us understand where the user interaction
2947 * was taking place. For example, if user is touching launcher, we will see a log that user
2948 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2949 * We will see both launcher and wallpaper in that list.
2950 * Once the interaction with a particular set of connections starts, no new logs will be printed
2951 * until the set of interacted connections changes.
2952 *
2953 * The following items are skipped, to reduce the logspam:
2954 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2955 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2956 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2957 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2958 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002959 */
2960void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2961 const std::vector<InputTarget>& targets) {
2962 // Skip ACTION_UP events, and all events other than keys and motions
2963 if (entry.type == EventEntry::Type::KEY) {
2964 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2965 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2966 return;
2967 }
2968 } else if (entry.type == EventEntry::Type::MOTION) {
2969 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2970 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2971 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2972 return;
2973 }
2974 } else {
2975 return; // Not a key or a motion
2976 }
2977
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07002978 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002979 std::vector<sp<Connection>> newConnections;
2980 for (const InputTarget& target : targets) {
2981 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2982 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2983 continue; // Skip windows that receive ACTION_OUTSIDE
2984 }
2985
2986 sp<IBinder> token = target.inputChannel->getConnectionToken();
2987 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002988 if (connection == nullptr) {
2989 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002990 }
2991 newConnectionTokens.insert(std::move(token));
2992 newConnections.emplace_back(connection);
2993 }
2994 if (newConnectionTokens == mInteractionConnectionTokens) {
2995 return; // no change
2996 }
2997 mInteractionConnectionTokens = newConnectionTokens;
2998
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002999 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003000 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003001 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003002 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003003 std::string message = "Interaction with: " + targetList;
3004 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003005 message += "<none>";
3006 }
3007 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3008}
3009
chaviwfd6d3512019-03-25 13:23:49 -07003010void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003011 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003012 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003013 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3014 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003015 return;
3016 }
3017
Vishnu Nairc519ff72021-01-21 08:23:08 -08003018 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003019 if (focusedToken == token) {
3020 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003021 return;
3022 }
3023
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003024 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3025 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003026 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003027 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028}
3029
3030void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003031 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003032 if (ATRACE_ENABLED()) {
3033 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003035 ATRACE_NAME(message.c_str());
3036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039#endif
3040
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003041 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3042 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003044 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003045 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003046 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047
3048 // Publish the event.
3049 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3051 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003052 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003053 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3054 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003056 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003057 status = connection->inputPublisher
3058 .publishKeyEvent(dispatchEntry->seq,
3059 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3060 keyEntry.source, keyEntry.displayId,
3061 std::move(hmac), dispatchEntry->resolvedAction,
3062 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3063 keyEntry.scanCode, keyEntry.metaState,
3064 keyEntry.repeatCount, keyEntry.downTime,
3065 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003066 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 }
3068
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003069 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003070 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003073 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074
chaviw82357092020-01-28 13:13:06 -08003075 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003076 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3078 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003079 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003080 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3081 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003082 // Don't apply window scale here since we don't want scale to affect raw
3083 // coordinates. The scale will be sent back to the client and applied
3084 // later when requesting relative coordinates.
3085 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3086 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 }
3088 usingCoords = scaledCoords;
3089 }
3090 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091 // We don't want the dispatch target to know.
3092 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003093 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 scaledCoords[i].clear();
3095 }
3096 usingCoords = scaledCoords;
3097 }
3098 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003099
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003100 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101
3102 // Publish the motion event.
3103 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003104 .publishMotionEvent(dispatchEntry->seq,
3105 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003106 motionEntry.deviceId, motionEntry.source,
3107 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003108 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003109 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003111 motionEntry.edgeFlags, motionEntry.metaState,
3112 motionEntry.buttonState,
3113 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003114 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003115 motionEntry.xPrecision, motionEntry.yPrecision,
3116 motionEntry.xCursorPosition,
3117 motionEntry.yCursorPosition,
3118 motionEntry.downTime, motionEntry.eventTime,
3119 motionEntry.pointerCount,
3120 motionEntry.pointerProperties, usingCoords);
3121 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 break;
3123 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003124
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003125 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003127 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003128 focusEntry.id,
3129 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003130 mInTouchMode);
3131 break;
3132 }
3133
Prabir Pradhan99987712020-11-10 18:43:05 -08003134 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3135 const auto& captureEntry =
3136 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3137 status = connection->inputPublisher
3138 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3139 captureEntry.pointerCaptureEnabled);
3140 break;
3141 }
3142
arthurhungb89ccb02020-12-30 16:19:01 +08003143 case EventEntry::Type::DRAG: {
3144 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3145 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3146 dragEntry.id, dragEntry.x,
3147 dragEntry.y,
3148 dragEntry.isExiting);
3149 break;
3150 }
3151
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003152 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003153 case EventEntry::Type::DEVICE_RESET:
3154 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003155 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003156 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160
3161 // Check the result.
3162 if (status) {
3163 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003164 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003166 "This is unexpected because the wait queue is empty, so the pipe "
3167 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003168 "event to it, status=%s(%d)",
3169 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3170 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3172 } else {
3173 // Pipe is full and we are waiting for the app to finish process some events
3174 // before sending more events to it.
3175#if DEBUG_DISPATCH_CYCLE
3176 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 "waiting for the application to catch up",
3178 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181 } else {
3182 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003183 "status=%s(%d)",
3184 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3185 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3187 }
3188 return;
3189 }
3190
3191 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003192 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3193 connection->outboundQueue.end(),
3194 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003195 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003196 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003197 if (connection->responsive) {
3198 mAnrTracker.insert(dispatchEntry->timeoutTime,
3199 connection->inputChannel->getConnectionToken());
3200 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003201 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202 }
3203}
3204
chaviw09c8d2d2020-08-24 15:48:26 -07003205std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3206 size_t size;
3207 switch (event.type) {
3208 case VerifiedInputEvent::Type::KEY: {
3209 size = sizeof(VerifiedKeyEvent);
3210 break;
3211 }
3212 case VerifiedInputEvent::Type::MOTION: {
3213 size = sizeof(VerifiedMotionEvent);
3214 break;
3215 }
3216 }
3217 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3218 return mHmacKeyManager.sign(start, size);
3219}
3220
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003221const std::array<uint8_t, 32> InputDispatcher::getSignature(
3222 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3223 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3224 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3225 // Only sign events up and down events as the purely move events
3226 // are tied to their up/down counterparts so signing would be redundant.
3227 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3228 verifiedEvent.actionMasked = actionMasked;
3229 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003230 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003231 }
3232 return INVALID_HMAC;
3233}
3234
3235const std::array<uint8_t, 32> InputDispatcher::getSignature(
3236 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3237 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3238 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3239 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003240 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003241}
3242
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003245 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246#if DEBUG_DISPATCH_CYCLE
3247 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249#endif
3250
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 if (connection->status == Connection::STATUS_BROKEN ||
3252 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 return;
3254 }
3255
3256 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003257 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258}
3259
3260void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 const sp<Connection>& connection,
3262 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263#if DEBUG_DISPATCH_CYCLE
3264 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266#endif
3267
3268 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003269 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003270 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003271 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003272 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
3274 // The connection appears to be unrecoverably broken.
3275 // Ignore already broken or zombie connections.
3276 if (connection->status == Connection::STATUS_NORMAL) {
3277 connection->status = Connection::STATUS_BROKEN;
3278
3279 if (notify) {
3280 // Notify other system components.
3281 onDispatchCycleBrokenLocked(currentTime, connection);
3282 }
3283 }
3284}
3285
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003286void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3287 while (!queue.empty()) {
3288 DispatchEntry* dispatchEntry = queue.front();
3289 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003290 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 }
3292}
3293
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003294void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 }
3298 delete dispatchEntry;
3299}
3300
3301int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3302 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3303
3304 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003305 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003307 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 "fd=%d, events=0x%x",
3310 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 return 0; // remove the callback
3312 }
3313
3314 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003315 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3317 if (!(events & ALOOPER_EVENT_INPUT)) {
3318 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 "events=0x%x",
3320 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 return 1;
3322 }
3323
3324 nsecs_t currentTime = now();
3325 bool gotOne = false;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00003326 status_t status = OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 for (;;) {
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003328 Result<InputPublisher::ConsumerResponse> result =
3329 connection->inputPublisher.receiveConsumerResponse();
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00003330 if (!result.ok()) {
3331 status = result.error().code();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 break;
3333 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003334
3335 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3336 const InputPublisher::Finished& finish =
3337 std::get<InputPublisher::Finished>(*result);
3338 d->finishDispatchCycleLocked(currentTime, connection, finish.seq,
3339 finish.handled, finish.consumeTime);
3340 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
3341 // TODO(b/167947340): Report this data to LatencyTracker
3342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 gotOne = true;
3344 }
3345 if (gotOne) {
3346 d->runCommandsLockedInterruptible();
3347 if (status == WOULD_BLOCK) {
3348 return 1;
3349 }
3350 }
3351
3352 notify = status != DEAD_OBJECT || !connection->monitor;
3353 if (notify) {
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003354 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3355 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3356 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 }
3358 } else {
3359 // Monitor channels are never explicitly unregistered.
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003360 // We do it automatically when the remote endpoint is closed so don't warn about them.
arthurhungd352cb32020-04-28 17:09:28 +08003361 const bool stillHaveWindowHandle =
3362 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3363 nullptr;
3364 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 if (notify) {
3366 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 "events=0x%x",
3368 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 }
3370 }
3371
Garfield Tan15601662020-09-22 15:32:38 -07003372 // Remove the channel.
3373 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003375 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376}
3377
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003380 for (const auto& [fd, connection] : mConnectionsByFd) {
3381 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 }
3383}
3384
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003386 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003387 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3388 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3389}
3390
3391void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3392 const CancelationOptions& options,
3393 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3394 for (const auto& it : monitorsByDisplay) {
3395 const std::vector<Monitor>& monitors = it.second;
3396 for (const Monitor& monitor : monitors) {
3397 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003398 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003399 }
3400}
3401
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003403 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003404 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003405 if (connection == nullptr) {
3406 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003408
3409 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410}
3411
3412void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3413 const sp<Connection>& connection, const CancelationOptions& options) {
3414 if (connection->status == Connection::STATUS_BROKEN) {
3415 return;
3416 }
3417
3418 nsecs_t currentTime = now();
3419
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003420 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003421 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003423 if (cancelationEvents.empty()) {
3424 return;
3425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003427 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3428 "with reality: %s, mode=%d.",
3429 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3430 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003432
3433 InputTarget target;
3434 sp<InputWindowHandle> windowHandle =
3435 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3436 if (windowHandle != nullptr) {
3437 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003438 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003439 target.globalScaleFactor = windowInfo->globalScaleFactor;
3440 }
3441 target.inputChannel = connection->inputChannel;
3442 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3443
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003444 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003445 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003446 switch (cancelationEventEntry->type) {
3447 case EventEntry::Type::KEY: {
3448 logOutboundKeyDetails("cancel - ",
3449 static_cast<const KeyEntry&>(*cancelationEventEntry));
3450 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003452 case EventEntry::Type::MOTION: {
3453 logOutboundMotionDetails("cancel - ",
3454 static_cast<const MotionEntry&>(*cancelationEventEntry));
3455 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003457 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003458 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3459 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003460 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003461 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003462 break;
3463 }
3464 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003465 case EventEntry::Type::DEVICE_RESET:
3466 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003467 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003468 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003469 break;
3470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003473 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3474 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003476
3477 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478}
3479
Svet Ganov5d3bc372020-01-26 23:11:07 -08003480void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3481 const sp<Connection>& connection) {
3482 if (connection->status == Connection::STATUS_BROKEN) {
3483 return;
3484 }
3485
3486 nsecs_t currentTime = now();
3487
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003488 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003489 connection->inputState.synthesizePointerDownEvents(currentTime);
3490
3491 if (downEvents.empty()) {
3492 return;
3493 }
3494
3495#if DEBUG_OUTBOUND_EVENT_DETAILS
3496 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3497 connection->getInputChannelName().c_str(), downEvents.size());
3498#endif
3499
3500 InputTarget target;
3501 sp<InputWindowHandle> windowHandle =
3502 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3503 if (windowHandle != nullptr) {
3504 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003505 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003506 target.globalScaleFactor = windowInfo->globalScaleFactor;
3507 }
3508 target.inputChannel = connection->inputChannel;
3509 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003511 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003512 switch (downEventEntry->type) {
3513 case EventEntry::Type::MOTION: {
3514 logOutboundMotionDetails("down - ",
3515 static_cast<const MotionEntry&>(*downEventEntry));
3516 break;
3517 }
3518
3519 case EventEntry::Type::KEY:
3520 case EventEntry::Type::FOCUS:
3521 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003522 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003523 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003524 case EventEntry::Type::SENSOR:
3525 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003526 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003527 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003528 break;
3529 }
3530 }
3531
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003532 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3533 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003534 }
3535
3536 startDispatchCycleLocked(currentTime, connection);
3537}
3538
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003539std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3540 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 ALOG_ASSERT(pointerIds.value != 0);
3542
3543 uint32_t splitPointerIndexMap[MAX_POINTERS];
3544 PointerProperties splitPointerProperties[MAX_POINTERS];
3545 PointerCoords splitPointerCoords[MAX_POINTERS];
3546
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003547 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 uint32_t splitPointerCount = 0;
3549
3550 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003551 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003553 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 uint32_t pointerId = uint32_t(pointerProperties.id);
3555 if (pointerIds.hasBit(pointerId)) {
3556 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3557 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3558 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003559 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 splitPointerCount += 1;
3561 }
3562 }
3563
3564 if (splitPointerCount != pointerIds.count()) {
3565 // This is bad. We are missing some of the pointers that we expected to deliver.
3566 // Most likely this indicates that we received an ACTION_MOVE events that has
3567 // different pointer ids than we expected based on the previous ACTION_DOWN
3568 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3569 // in this way.
3570 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003571 "we expected there to be %d pointers. This probably means we received "
3572 "a broken sequence of pointer ids from the input device.",
3573 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003574 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 }
3576
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003577 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003579 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3580 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3582 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003583 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 uint32_t pointerId = uint32_t(pointerProperties.id);
3585 if (pointerIds.hasBit(pointerId)) {
3586 if (pointerIds.count() == 1) {
3587 // The first/last pointer went down/up.
3588 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003590 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3591 ? AMOTION_EVENT_ACTION_CANCEL
3592 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 } else {
3594 // A secondary pointer went down/up.
3595 uint32_t splitPointerIndex = 0;
3596 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3597 splitPointerIndex += 1;
3598 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003599 action = maskedAction |
3600 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 }
3602 } else {
3603 // An unrelated pointer changed.
3604 action = AMOTION_EVENT_ACTION_MOVE;
3605 }
3606 }
3607
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003608 int32_t newId = mIdGenerator.nextId();
3609 if (ATRACE_ENABLED()) {
3610 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3611 ") to MotionEvent(id=0x%" PRIx32 ").",
3612 originalMotionEntry.id, newId);
3613 ATRACE_NAME(message.c_str());
3614 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003615 std::unique_ptr<MotionEntry> splitMotionEntry =
3616 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3617 originalMotionEntry.deviceId, originalMotionEntry.source,
3618 originalMotionEntry.displayId,
3619 originalMotionEntry.policyFlags, action,
3620 originalMotionEntry.actionButton,
3621 originalMotionEntry.flags, originalMotionEntry.metaState,
3622 originalMotionEntry.buttonState,
3623 originalMotionEntry.classification,
3624 originalMotionEntry.edgeFlags,
3625 originalMotionEntry.xPrecision,
3626 originalMotionEntry.yPrecision,
3627 originalMotionEntry.xCursorPosition,
3628 originalMotionEntry.yCursorPosition,
3629 originalMotionEntry.downTime, splitPointerCount,
3630 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003632 if (originalMotionEntry.injectionState) {
3633 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 splitMotionEntry->injectionState->refCount += 1;
3635 }
3636
3637 return splitMotionEntry;
3638}
3639
3640void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3641#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003642 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643#endif
3644
3645 bool needWake;
3646 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003647 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003649 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3650 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3651 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 } // release lock
3653
3654 if (needWake) {
3655 mLooper->wake();
3656 }
3657}
3658
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003659/**
3660 * If one of the meta shortcuts is detected, process them here:
3661 * Meta + Backspace -> generate BACK
3662 * Meta + Enter -> generate HOME
3663 * This will potentially overwrite keyCode and metaState.
3664 */
3665void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003666 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003667 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3668 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3669 if (keyCode == AKEYCODE_DEL) {
3670 newKeyCode = AKEYCODE_BACK;
3671 } else if (keyCode == AKEYCODE_ENTER) {
3672 newKeyCode = AKEYCODE_HOME;
3673 }
3674 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003675 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003676 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003677 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003678 keyCode = newKeyCode;
3679 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3680 }
3681 } else if (action == AKEY_EVENT_ACTION_UP) {
3682 // In order to maintain a consistent stream of up and down events, check to see if the key
3683 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3684 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003685 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003686 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003687 auto replacementIt = mReplacedKeys.find(replacement);
3688 if (replacementIt != mReplacedKeys.end()) {
3689 keyCode = replacementIt->second;
3690 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003691 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3692 }
3693 }
3694}
3695
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3697#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003698 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3699 "policyFlags=0x%x, action=0x%x, "
3700 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3701 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3702 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3703 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704#endif
3705 if (!validateKeyEvent(args->action)) {
3706 return;
3707 }
3708
3709 uint32_t policyFlags = args->policyFlags;
3710 int32_t flags = args->flags;
3711 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003712 // InputDispatcher tracks and generates key repeats on behalf of
3713 // whatever notifies it, so repeatCount should always be set to 0
3714 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3716 policyFlags |= POLICY_FLAG_VIRTUAL;
3717 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 if (policyFlags & POLICY_FLAG_FUNCTION) {
3720 metaState |= AMETA_FUNCTION_ON;
3721 }
3722
3723 policyFlags |= POLICY_FLAG_TRUSTED;
3724
Michael Wright78f24442014-08-06 15:55:28 -07003725 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003726 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003727
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003729 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003730 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3731 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732
Michael Wright2b3c3302018-03-02 17:19:13 +00003733 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003735 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3736 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003737 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 bool needWake;
3741 { // acquire lock
3742 mLock.lock();
3743
3744 if (shouldSendKeyToInputFilterLocked(args)) {
3745 mLock.unlock();
3746
3747 policyFlags |= POLICY_FLAG_FILTERED;
3748 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3749 return; // event was consumed by the filter
3750 }
3751
3752 mLock.lock();
3753 }
3754
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003755 std::unique_ptr<KeyEntry> newEntry =
3756 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3757 args->displayId, policyFlags, args->action, flags,
3758 keyCode, args->scanCode, metaState, repeatCount,
3759 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003761 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 mLock.unlock();
3763 } // release lock
3764
3765 if (needWake) {
3766 mLooper->wake();
3767 }
3768}
3769
3770bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3771 return mInputFilterEnabled;
3772}
3773
3774void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3775#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003776 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3777 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003778 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3779 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003780 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003781 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3782 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3783 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3784 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 for (uint32_t i = 0; i < args->pointerCount; i++) {
3786 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 "x=%f, y=%f, pressure=%f, size=%f, "
3788 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3789 "orientation=%f",
3790 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3791 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3792 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3793 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3794 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3795 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3796 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3797 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3798 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3799 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
3801#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003802 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3803 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 return;
3805 }
3806
3807 uint32_t policyFlags = args->policyFlags;
3808 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003809
3810 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003811 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003812 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3813 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816
3817 bool needWake;
3818 { // acquire lock
3819 mLock.lock();
3820
3821 if (shouldSendMotionToInputFilterLocked(args)) {
3822 mLock.unlock();
3823
3824 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003825 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003826 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3827 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003828 args->metaState, args->buttonState, args->classification, transform,
3829 args->xPrecision, args->yPrecision, args->xCursorPosition,
3830 args->yCursorPosition, args->downTime, args->eventTime,
3831 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
3833 policyFlags |= POLICY_FLAG_FILTERED;
3834 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3835 return; // event was consumed by the filter
3836 }
3837
3838 mLock.lock();
3839 }
3840
3841 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003842 std::unique_ptr<MotionEntry> newEntry =
3843 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3844 args->source, args->displayId, policyFlags,
3845 args->action, args->actionButton, args->flags,
3846 args->metaState, args->buttonState,
3847 args->classification, args->edgeFlags,
3848 args->xPrecision, args->yPrecision,
3849 args->xCursorPosition, args->yCursorPosition,
3850 args->downTime, args->pointerCount,
3851 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003853 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 mLock.unlock();
3855 } // release lock
3856
3857 if (needWake) {
3858 mLooper->wake();
3859 }
3860}
3861
Chris Yef59a2f42020-10-16 12:55:26 -07003862void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3863#if DEBUG_INBOUND_EVENT_DETAILS
3864 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3865 " sensorType=%s",
3866 args->id, args->eventTime, args->deviceId, args->source,
3867 NamedEnum::string(args->sensorType).c_str());
3868#endif
3869
3870 bool needWake;
3871 { // acquire lock
3872 mLock.lock();
3873
3874 // Just enqueue a new sensor event.
3875 std::unique_ptr<SensorEntry> newEntry =
3876 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3877 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3878 args->sensorType, args->accuracy,
3879 args->accuracyChanged, args->values);
3880
3881 needWake = enqueueInboundEventLocked(std::move(newEntry));
3882 mLock.unlock();
3883 } // release lock
3884
3885 if (needWake) {
3886 mLooper->wake();
3887 }
3888}
3889
Chris Yefb552902021-02-03 17:18:37 -08003890void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3891#if DEBUG_INBOUND_EVENT_DETAILS
3892 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3893 args->deviceId, args->isOn);
3894#endif
3895 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3896}
3897
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003899 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900}
3901
3902void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3903#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003904 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003905 "switchMask=0x%08x",
3906 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907#endif
3908
3909 uint32_t policyFlags = args->policyFlags;
3910 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003911 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912}
3913
3914void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3915#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003916 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3917 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918#endif
3919
3920 bool needWake;
3921 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003922 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003924 std::unique_ptr<DeviceResetEntry> newEntry =
3925 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3926 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 } // release lock
3928
3929 if (needWake) {
3930 mLooper->wake();
3931 }
3932}
3933
Prabir Pradhan7e186182020-11-10 13:56:45 -08003934void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3935#if DEBUG_INBOUND_EVENT_DETAILS
3936 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3937 args->enabled ? "true" : "false");
3938#endif
3939
Prabir Pradhan99987712020-11-10 18:43:05 -08003940 bool needWake;
3941 { // acquire lock
3942 std::scoped_lock _l(mLock);
3943 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3944 args->enabled);
3945 needWake = enqueueInboundEventLocked(std::move(entry));
3946 } // release lock
3947
3948 if (needWake) {
3949 mLooper->wake();
3950 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003951}
3952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953InputEventInjectionResult InputDispatcher::injectInputEvent(
3954 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3955 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956#if DEBUG_INBOUND_EVENT_DETAILS
3957 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003958 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3959 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003961 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
3963 policyFlags |= POLICY_FLAG_INJECTED;
3964 if (hasInjectionPermission(injectorPid, injectorUid)) {
3965 policyFlags |= POLICY_FLAG_TRUSTED;
3966 }
3967
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003968 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003971 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3972 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003974 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003977 int32_t flags = incomingKey.getFlags();
3978 int32_t keyCode = incomingKey.getKeyCode();
3979 int32_t metaState = incomingKey.getMetaState();
3980 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003982 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003983 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003984 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3985 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3986 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003988 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3989 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003990 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003991
3992 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3993 android::base::Timer t;
3994 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3995 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3996 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3997 std::to_string(t.duration().count()).c_str());
3998 }
3999 }
4000
4001 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::unique_ptr<KeyEntry> injectedEntry =
4003 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
4004 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
4005 incomingKey.getDisplayId(), policyFlags, action,
4006 flags, keyCode, incomingKey.getScanCode(), metaState,
4007 incomingKey.getRepeatCount(),
4008 incomingKey.getDownTime());
4009 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 }
4012
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004013 case AINPUT_EVENT_TYPE_MOTION: {
4014 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
4015 int32_t action = motionEvent->getAction();
4016 size_t pointerCount = motionEvent->getPointerCount();
4017 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
4018 int32_t actionButton = motionEvent->getActionButton();
4019 int32_t displayId = motionEvent->getDisplayId();
4020 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004021 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 }
4023
4024 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4025 nsecs_t eventTime = motionEvent->getEventTime();
4026 android::base::Timer t;
4027 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4028 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4029 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4030 std::to_string(t.duration().count()).c_str());
4031 }
4032 }
4033
4034 mLock.lock();
4035 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
4036 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004037 std::unique_ptr<MotionEntry> injectedEntry =
4038 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4039 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4040 motionEvent->getDisplayId(), policyFlags, action,
4041 actionButton, motionEvent->getFlags(),
4042 motionEvent->getMetaState(),
4043 motionEvent->getButtonState(),
4044 motionEvent->getClassification(),
4045 motionEvent->getEdgeFlags(),
4046 motionEvent->getXPrecision(),
4047 motionEvent->getYPrecision(),
4048 motionEvent->getRawXCursorPosition(),
4049 motionEvent->getRawYCursorPosition(),
4050 motionEvent->getDownTime(),
4051 uint32_t(pointerCount), pointerProperties,
4052 samplePointerCoords, motionEvent->getXOffset(),
4053 motionEvent->getYOffset());
4054 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
4056 sampleEventTimes += 1;
4057 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004058 std::unique_ptr<MotionEntry> nextInjectedEntry =
4059 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4060 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4061 motionEvent->getDisplayId(), policyFlags,
4062 action, actionButton, motionEvent->getFlags(),
4063 motionEvent->getMetaState(),
4064 motionEvent->getButtonState(),
4065 motionEvent->getClassification(),
4066 motionEvent->getEdgeFlags(),
4067 motionEvent->getXPrecision(),
4068 motionEvent->getYPrecision(),
4069 motionEvent->getRawXCursorPosition(),
4070 motionEvent->getRawYCursorPosition(),
4071 motionEvent->getDownTime(),
4072 uint32_t(pointerCount), pointerProperties,
4073 samplePointerCoords,
4074 motionEvent->getXOffset(),
4075 motionEvent->getYOffset());
4076 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 }
4078 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004082 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004083 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 }
4085
4086 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004087 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 injectionState->injectionIsAsync = true;
4089 }
4090
4091 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004092 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093
4094 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004095 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004096 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004097 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
4099
4100 mLock.unlock();
4101
4102 if (needWake) {
4103 mLooper->wake();
4104 }
4105
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004106 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004108 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004110 if (syncMode == InputEventInjectionSync::NONE) {
4111 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 } else {
4113 for (;;) {
4114 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004115 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 break;
4117 }
4118
4119 nsecs_t remainingTimeout = endTime - now();
4120 if (remainingTimeout <= 0) {
4121#if DEBUG_INJECTION
4122 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004125 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 break;
4127 }
4128
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004129 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 }
4131
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004132 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4133 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 while (injectionState->pendingForegroundDispatches != 0) {
4135#if DEBUG_INJECTION
4136 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138#endif
4139 nsecs_t remainingTimeout = endTime - now();
4140 if (remainingTimeout <= 0) {
4141#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4143 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004145 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 break;
4147 }
4148
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004149 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 }
4151 }
4152 }
4153
4154 injectionState->release();
4155 } // release lock
4156
4157#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004158 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004159 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160#endif
4161
4162 return injectionResult;
4163}
4164
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004165std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004166 std::array<uint8_t, 32> calculatedHmac;
4167 std::unique_ptr<VerifiedInputEvent> result;
4168 switch (event.getType()) {
4169 case AINPUT_EVENT_TYPE_KEY: {
4170 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4171 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4172 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004173 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004174 break;
4175 }
4176 case AINPUT_EVENT_TYPE_MOTION: {
4177 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4178 VerifiedMotionEvent verifiedMotionEvent =
4179 verifiedMotionEventFromMotionEvent(motionEvent);
4180 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004181 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004182 break;
4183 }
4184 default: {
4185 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4186 return nullptr;
4187 }
4188 }
4189 if (calculatedHmac == INVALID_HMAC) {
4190 return nullptr;
4191 }
4192 if (calculatedHmac != event.getHmac()) {
4193 return nullptr;
4194 }
4195 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004196}
4197
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004199 return injectorUid == 0 ||
4200 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201}
4202
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004203void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004204 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004205 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 if (injectionState) {
4207#if DEBUG_INJECTION
4208 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 "injectorPid=%d, injectorUid=%d",
4210 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211#endif
4212
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004213 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 // Log the outcome since the injector did not wait for the injection result.
4215 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004216 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 ALOGV("Asynchronous input event injection succeeded.");
4218 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 ALOGW("Asynchronous input event injection failed.");
4221 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004222 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 ALOGW("Asynchronous input event injection permission denied.");
4224 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004225 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 ALOGW("Asynchronous input event injection timed out.");
4227 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004228 case InputEventInjectionResult::PENDING:
4229 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4230 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232 }
4233
4234 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004235 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237}
4238
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004239void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4240 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 if (injectionState) {
4242 injectionState->pendingForegroundDispatches += 1;
4243 }
4244}
4245
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004246void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4247 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 if (injectionState) {
4249 injectionState->pendingForegroundDispatches -= 1;
4250
4251 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004252 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 }
4254 }
4255}
4256
Vishnu Nairad321cd2020-08-20 16:40:21 -07004257const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004258 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004259 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4260 auto it = mWindowHandlesByDisplay.find(displayId);
4261 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004262}
4263
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004265 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004266 if (windowHandleToken == nullptr) {
4267 return nullptr;
4268 }
4269
Arthur Hungb92218b2018-08-14 12:00:21 +08004270 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004271 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004272 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004273 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004274 return windowHandle;
4275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 }
4277 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004278 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279}
4280
Vishnu Nairad321cd2020-08-20 16:40:21 -07004281sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4282 int displayId) const {
4283 if (windowHandleToken == nullptr) {
4284 return nullptr;
4285 }
4286
4287 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4288 if (windowHandle->getToken() == windowHandleToken) {
4289 return windowHandle;
4290 }
4291 }
4292 return nullptr;
4293}
4294
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004295sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4296 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004297 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004298 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004299 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004300 if (handle->getId() == windowHandle->getId() &&
4301 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004302 if (windowHandle->getInfo()->displayId != it.first) {
4303 ALOGE("Found window %s in display %" PRId32
4304 ", but it should belong to display %" PRId32,
4305 windowHandle->getName().c_str(), it.first,
4306 windowHandle->getInfo()->displayId);
4307 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004308 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004312 return nullptr;
4313}
4314
4315sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4316 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4317 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318}
4319
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004320bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4321 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4322 const bool noInputChannel =
4323 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4324 if (connection != nullptr && noInputChannel) {
4325 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4326 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4327 return false;
4328 }
4329
4330 if (connection == nullptr) {
4331 if (!noInputChannel) {
4332 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4333 }
4334 return false;
4335 }
4336 if (!connection->responsive) {
4337 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4338 return false;
4339 }
4340 return true;
4341}
4342
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004343std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4344 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004345 size_t count = mInputChannelsByToken.count(token);
4346 if (count == 0) {
4347 return nullptr;
4348 }
4349 return mInputChannelsByToken.at(token);
4350}
4351
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004352void InputDispatcher::updateWindowHandlesForDisplayLocked(
4353 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4354 if (inputWindowHandles.empty()) {
4355 // Remove all handles on a display if there are no windows left.
4356 mWindowHandlesByDisplay.erase(displayId);
4357 return;
4358 }
4359
4360 // Since we compare the pointer of input window handles across window updates, we need
4361 // to make sure the handle object for the same window stays unchanged across updates.
4362 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004363 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004364 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004365 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004366 }
4367
4368 std::vector<sp<InputWindowHandle>> newHandles;
4369 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4370 if (!handle->updateInfo()) {
4371 // handle no longer valid
4372 continue;
4373 }
4374
4375 const InputWindowInfo* info = handle->getInfo();
4376 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4377 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4378 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004379 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4380 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4381 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004382 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004383 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004384 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004385 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004386 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004387 }
4388
4389 if (info->displayId != displayId) {
4390 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4391 handle->getName().c_str(), displayId, info->displayId);
4392 continue;
4393 }
4394
Robert Carredd13602020-04-13 17:24:34 -07004395 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4396 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004397 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004398 oldHandle->updateFrom(handle);
4399 newHandles.push_back(oldHandle);
4400 } else {
4401 newHandles.push_back(handle);
4402 }
4403 }
4404
4405 // Insert or replace
4406 mWindowHandlesByDisplay[displayId] = newHandles;
4407}
4408
Arthur Hung72d8dc32020-03-28 00:48:39 +00004409void InputDispatcher::setInputWindows(
4410 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4411 { // acquire lock
4412 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004413 for (const auto& [displayId, handles] : handlesPerDisplay) {
4414 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004415 }
4416 }
4417 // Wake up poll loop since it may need to make new input dispatching choices.
4418 mLooper->wake();
4419}
4420
Arthur Hungb92218b2018-08-14 12:00:21 +08004421/**
4422 * Called from InputManagerService, update window handle list by displayId that can receive input.
4423 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4424 * If set an empty list, remove all handles from the specific display.
4425 * For focused handle, check if need to change and send a cancel event to previous one.
4426 * For removed handle, check if need to send a cancel event if already in touch.
4427 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004428void InputDispatcher::setInputWindowsLocked(
4429 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004430 if (DEBUG_FOCUS) {
4431 std::string windowList;
4432 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4433 windowList += iwh->getName() + " ";
4434 }
4435 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004438 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4439 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4440 const bool noInputWindow =
4441 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4442 if (noInputWindow && window->getToken() != nullptr) {
4443 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4444 window->getName().c_str());
4445 window->releaseChannel();
4446 }
4447 }
4448
Arthur Hung72d8dc32020-03-28 00:48:39 +00004449 // Copy old handles for release if they are no longer present.
4450 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004452 // Save the old windows' orientation by ID before it gets updated.
4453 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4454 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4455 oldWindowOrientations.emplace(handle->getId(),
4456 handle->getInfo()->transform.getOrientation());
4457 }
4458
Arthur Hung72d8dc32020-03-28 00:48:39 +00004459 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004460
Vishnu Nair958da932020-08-21 17:12:37 -07004461 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4462 if (mLastHoverWindowHandle &&
4463 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4464 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004465 mLastHoverWindowHandle = nullptr;
4466 }
4467
Vishnu Nairc519ff72021-01-21 08:23:08 -08004468 std::optional<FocusResolver::FocusChanges> changes =
4469 mFocusResolver.setInputWindows(displayId, windowHandles);
4470 if (changes) {
4471 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004474 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4475 mTouchStatesByDisplay.find(displayId);
4476 if (stateIt != mTouchStatesByDisplay.end()) {
4477 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004478 for (size_t i = 0; i < state.windows.size();) {
4479 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004480 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004481 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004482 ALOGD("Touched window was removed: %s in display %" PRId32,
4483 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004484 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004485 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004486 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4487 if (touchedInputChannel != nullptr) {
4488 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4489 "touched window was removed");
4490 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004492 state.windows.erase(state.windows.begin() + i);
4493 } else {
4494 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 }
4496 }
arthurhungb89ccb02020-12-30 16:19:01 +08004497
arthurhung6d4bed92021-03-17 11:59:33 +08004498 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004499 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004500 if (mDragState &&
4501 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004502 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004503 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004504 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004505 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004506
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004507 if (isPerWindowInputRotationEnabled()) {
4508 // Determine if the orientation of any of the input windows have changed, and cancel all
4509 // pointer events if necessary.
4510 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4511 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4512 if (newWindowHandle != nullptr &&
4513 newWindowHandle->getInfo()->transform.getOrientation() !=
4514 oldWindowOrientations[oldWindowHandle->getId()]) {
4515 std::shared_ptr<InputChannel> inputChannel =
4516 getInputChannelLocked(newWindowHandle->getToken());
4517 if (inputChannel != nullptr) {
4518 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4519 "touched window's orientation changed");
4520 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4521 }
4522 }
4523 }
4524 }
4525
Arthur Hung72d8dc32020-03-28 00:48:39 +00004526 // Release information for windows that are no longer present.
4527 // This ensures that unused input channels are released promptly.
4528 // Otherwise, they might stick around until the window handle is destroyed
4529 // which might not happen until the next GC.
4530 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004531 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004532 if (DEBUG_FOCUS) {
4533 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004534 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004535 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004536 // To avoid making too many calls into the compat framework, only
4537 // check for window flags when windows are going away.
4538 // TODO(b/157929241) : delete this. This is only needed temporarily
4539 // in order to gather some data about the flag usage
4540 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4541 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4542 oldWindowHandle->getName().c_str());
4543 if (mCompatService != nullptr) {
4544 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4545 oldWindowHandle->getInfo()->ownerUid);
4546 }
4547 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004548 }
chaviw291d88a2019-02-14 10:33:58 -08004549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550}
4551
4552void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004553 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004554 if (DEBUG_FOCUS) {
4555 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4556 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4557 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004558 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004559 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560
Chris Yea209fde2020-07-22 13:54:51 -07004561 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004562 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004563
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004564 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4565 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566 }
4567
Chris Yea209fde2020-07-22 13:54:51 -07004568 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004569 if (inputApplicationHandle != nullptr) {
4570 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4571 } else {
4572 mFocusedApplicationHandlesByDisplay.erase(displayId);
4573 }
4574
4575 // No matter what the old focused application was, stop waiting on it because it is
4576 // no longer focused.
4577 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 } // release lock
4579
4580 // Wake up poll loop since it may need to make new input dispatching choices.
4581 mLooper->wake();
4582}
4583
Tiger Huang721e26f2018-07-24 22:26:19 +08004584/**
4585 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4586 * the display not specified.
4587 *
4588 * We track any unreleased events for each window. If a window loses the ability to receive the
4589 * released event, we will send a cancel event to it. So when the focused display is changed, we
4590 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4591 * display. The display-specified events won't be affected.
4592 */
4593void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004594 if (DEBUG_FOCUS) {
4595 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4596 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004597 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004598 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004599
4600 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004601 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004602 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004603 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004604 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004605 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004606 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004607 CancelationOptions
4608 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4609 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004610 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004611 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4612 }
4613 }
4614 mFocusedDisplayId = displayId;
4615
Chris Ye3c2d6f52020-08-09 10:39:48 -07004616 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004617 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004618 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004619
Vishnu Nairad321cd2020-08-20 16:40:21 -07004620 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004621 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004622 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004623 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004624 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004625 }
4626 }
4627 }
4628
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004629 if (DEBUG_FOCUS) {
4630 logDispatchStateLocked();
4631 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004632 } // release lock
4633
4634 // Wake up poll loop since it may need to make new input dispatching choices.
4635 mLooper->wake();
4636}
4637
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004639 if (DEBUG_FOCUS) {
4640 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642
4643 bool changed;
4644 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004645 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646
4647 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4648 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 }
4651
4652 if (mDispatchEnabled && !enabled) {
4653 resetAndDropEverythingLocked("dispatcher is being disabled");
4654 }
4655
4656 mDispatchEnabled = enabled;
4657 mDispatchFrozen = frozen;
4658 changed = true;
4659 } else {
4660 changed = false;
4661 }
4662
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004663 if (DEBUG_FOCUS) {
4664 logDispatchStateLocked();
4665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 } // release lock
4667
4668 if (changed) {
4669 // Wake up poll loop since it may need to make new input dispatching choices.
4670 mLooper->wake();
4671 }
4672}
4673
4674void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004675 if (DEBUG_FOCUS) {
4676 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678
4679 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004680 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681
4682 if (mInputFilterEnabled == enabled) {
4683 return;
4684 }
4685
4686 mInputFilterEnabled = enabled;
4687 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4688 } // release lock
4689
4690 // Wake up poll loop since there might be work to do to drop everything.
4691 mLooper->wake();
4692}
4693
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004694void InputDispatcher::setInTouchMode(bool inTouchMode) {
4695 std::scoped_lock lock(mLock);
4696 mInTouchMode = inTouchMode;
4697}
4698
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004699void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4700 if (opacity < 0 || opacity > 1) {
4701 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4702 return;
4703 }
4704
4705 std::scoped_lock lock(mLock);
4706 mMaximumObscuringOpacityForTouch = opacity;
4707}
4708
4709void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4710 std::scoped_lock lock(mLock);
4711 mBlockUntrustedTouchesMode = mode;
4712}
4713
arthurhungb89ccb02020-12-30 16:19:01 +08004714bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4715 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004716 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004717 if (DEBUG_FOCUS) {
4718 ALOGD("Trivial transfer to same window.");
4719 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004720 return true;
4721 }
4722
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004724 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
chaviwfbe5d9c2018-12-26 12:23:37 -08004726 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4727 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004728 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004729 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 return false;
4731 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004732 if (DEBUG_FOCUS) {
4733 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4734 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004737 if (DEBUG_FOCUS) {
4738 ALOGD("Cannot transfer focus because windows are on different displays.");
4739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 return false;
4741 }
4742
4743 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004744 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4745 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004746 for (size_t i = 0; i < state.windows.size(); i++) {
4747 const TouchedWindow& touchedWindow = state.windows[i];
4748 if (touchedWindow.windowHandle == fromWindowHandle) {
4749 int32_t oldTargetFlags = touchedWindow.targetFlags;
4750 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004752 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754 int32_t newTargetFlags = oldTargetFlags &
4755 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4756 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004757 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
arthurhungb89ccb02020-12-30 16:19:01 +08004759 // Store the dragging window.
4760 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004761 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004762 }
4763
Jeff Brownf086ddb2014-02-11 14:28:48 -08004764 found = true;
4765 goto Found;
4766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 }
4768 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004769 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004771 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004772 if (DEBUG_FOCUS) {
4773 ALOGD("Focus transfer failed because from window did not have focus.");
4774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 return false;
4776 }
4777
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004778 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4779 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004780 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004781 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004782 CancelationOptions
4783 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4784 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004786 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 }
4788
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004789 if (DEBUG_FOCUS) {
4790 logDispatchStateLocked();
4791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 } // release lock
4793
4794 // Wake up poll loop since it may need to make new input dispatching choices.
4795 mLooper->wake();
4796 return true;
4797}
4798
4799void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004800 if (DEBUG_FOCUS) {
4801 ALOGD("Resetting and dropping all events (%s).", reason);
4802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
4804 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4805 synthesizeCancelationEventsForAllConnectionsLocked(options);
4806
4807 resetKeyRepeatLocked();
4808 releasePendingEventLocked();
4809 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004810 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004812 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004813 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004815 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816}
4817
4818void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004819 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 dumpDispatchStateLocked(dump);
4821
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004822 std::istringstream stream(dump);
4823 std::string line;
4824
4825 while (std::getline(stream, line, '\n')) {
4826 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
4828}
4829
Prabir Pradhan99987712020-11-10 18:43:05 -08004830std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4831 std::string dump;
4832
4833 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4834 toString(mFocusedWindowRequestedPointerCapture));
4835
4836 std::string windowName = "None";
4837 if (mWindowTokenWithPointerCapture) {
4838 const sp<InputWindowHandle> captureWindowHandle =
4839 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4840 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4841 : "token has capture without window";
4842 }
4843 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4844
4845 return dump;
4846}
4847
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004848void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004849 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4850 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4851 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004852 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853
Tiger Huang721e26f2018-07-24 22:26:19 +08004854 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4855 dump += StringPrintf(INDENT "FocusedApplications:\n");
4856 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4857 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004858 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004859 const std::chrono::duration timeout =
4860 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004861 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004862 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004863 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004866 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004868
Vishnu Nairc519ff72021-01-21 08:23:08 -08004869 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004870 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004872 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004873 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004874 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4875 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004876 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004877 state.displayId, toString(state.down), toString(state.split),
4878 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004879 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004880 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004881 for (size_t i = 0; i < state.windows.size(); i++) {
4882 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004883 dump += StringPrintf(INDENT4
4884 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4885 i, touchedWindow.windowHandle->getName().c_str(),
4886 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004887 }
4888 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004889 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004890 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004891 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004892 dump += INDENT3 "Portal windows:\n";
4893 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004894 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004895 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4896 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004897 }
4898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 }
4900 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004901 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 }
4903
arthurhung6d4bed92021-03-17 11:59:33 +08004904 if (mDragState) {
4905 dump += StringPrintf(INDENT "DragState:\n");
4906 mDragState->dump(dump, INDENT2);
4907 }
4908
Arthur Hungb92218b2018-08-14 12:00:21 +08004909 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004910 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004911 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004912 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004913 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004914 dump += INDENT2 "Windows:\n";
4915 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004916 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004917 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004919 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004920 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004921 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004922 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004923 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004924 "applicationInfo.name=%s, "
4925 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004926 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004927 i, windowInfo->name.c_str(), windowInfo->id,
4928 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004929 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004930 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004931 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004932 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004933 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004934 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004935 windowInfo->frameLeft, windowInfo->frameTop,
4936 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004937 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004938 windowInfo->applicationInfo.name.c_str(),
4939 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004940 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004941 dump += StringPrintf(", inputFeatures=%s",
4942 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004943 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004944 "ms, trustedOverlay=%s, hasToken=%s, "
4945 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004946 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004947 millis(windowInfo->dispatchingTimeout),
4948 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004949 toString(windowInfo->token != nullptr),
4950 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004951 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004952 }
4953 } else {
4954 dump += INDENT2 "Windows: <none>\n";
4955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 }
4957 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004958 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
4960
Michael Wright3dd60e22019-03-27 22:06:44 +00004961 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004962 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004963 const std::vector<Monitor>& monitors = it.second;
4964 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4965 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004966 }
4967 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004968 const std::vector<Monitor>& monitors = it.second;
4969 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4970 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004973 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 }
4975
4976 nsecs_t currentTime = now();
4977
4978 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004979 if (!mRecentQueue.empty()) {
4980 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004981 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004982 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004983 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004984 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985 }
4986 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004987 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 }
4989
4990 // Dump event currently being dispatched.
4991 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004992 dump += INDENT "PendingEvent:\n";
4993 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004994 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004995 dump += StringPrintf(", age=%" PRId64 "ms\n",
4996 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004998 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999 }
5000
5001 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005002 if (!mInboundQueue.empty()) {
5003 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005004 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005005 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005006 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005007 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 }
5009 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005010 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005013 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005014 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005015 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5016 const KeyReplacement& replacement = pair.first;
5017 int32_t newKeyCode = pair.second;
5018 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005020 }
5021 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005022 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005023 }
5024
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005025 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005026 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005027 for (const auto& pair : mConnectionsByFd) {
5028 const sp<Connection>& connection = pair.second;
5029 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005030 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005031 pair.first, connection->getInputChannelName().c_str(),
5032 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005033 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005035 if (!connection->outboundQueue.empty()) {
5036 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5037 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005038 dump += dumpQueue(connection->outboundQueue, currentTime);
5039
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005041 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042 }
5043
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005044 if (!connection->waitQueue.empty()) {
5045 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5046 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005047 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005049 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 }
5051 }
5052 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005053 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005054 }
5055
5056 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005057 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5058 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005060 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
5062
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005063 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005064 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5065 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5066 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067}
5068
Michael Wright3dd60e22019-03-27 22:06:44 +00005069void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5070 const size_t numMonitors = monitors.size();
5071 for (size_t i = 0; i < numMonitors; i++) {
5072 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005073 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005074 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5075 dump += "\n";
5076 }
5077}
5078
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005079Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005080#if DEBUG_CHANNEL_CREATION
5081 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082#endif
5083
Garfield Tan15601662020-09-22 15:32:38 -07005084 std::shared_ptr<InputChannel> serverChannel;
5085 std::unique_ptr<InputChannel> clientChannel;
5086 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5087
5088 if (result) {
5089 return base::Error(result) << "Failed to open input channel pair with name " << name;
5090 }
5091
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005093 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07005094 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095
Garfield Tan15601662020-09-22 15:32:38 -07005096 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005097 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005098 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
5101 } // release lock
5102
5103 // Wake the looper because some connections have changed.
5104 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005105 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106}
5107
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005108Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5109 bool isGestureMonitor,
5110 const std::string& name,
5111 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005112 std::shared_ptr<InputChannel> serverChannel;
5113 std::unique_ptr<InputChannel> clientChannel;
5114 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5115 if (result) {
5116 return base::Error(result) << "Failed to open input channel pair with name " << name;
5117 }
5118
Michael Wright3dd60e22019-03-27 22:06:44 +00005119 { // acquire lock
5120 std::scoped_lock _l(mLock);
5121
5122 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005123 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5124 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005125 }
5126
Garfield Tan15601662020-09-22 15:32:38 -07005127 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00005128
Garfield Tan15601662020-09-22 15:32:38 -07005129 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005130 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005131 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005133 auto& monitorsByDisplay =
5134 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005135 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005136
5137 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00005138 }
Garfield Tan15601662020-09-22 15:32:38 -07005139
Michael Wright3dd60e22019-03-27 22:06:44 +00005140 // Wake the looper because some connections have changed.
5141 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005142 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005143}
5144
Garfield Tan15601662020-09-22 15:32:38 -07005145status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005147 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148
Garfield Tan15601662020-09-22 15:32:38 -07005149 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 if (status) {
5151 return status;
5152 }
5153 } // release lock
5154
5155 // Wake the poll loop because removing the connection may have changed the current
5156 // synchronization state.
5157 mLooper->wake();
5158 return OK;
5159}
5160
Garfield Tan15601662020-09-22 15:32:38 -07005161status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5162 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005163 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005164 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005165 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 return BAD_VALUE;
5167 }
5168
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005170 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005171
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005173 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 }
5175
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005176 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177
5178 nsecs_t currentTime = now();
5179 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5180
5181 connection->status = Connection::STATUS_ZOMBIE;
5182 return OK;
5183}
5184
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005185void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5186 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5187 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005188}
5189
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005190void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005191 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005192 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005193 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005194 std::vector<Monitor>& monitors = it->second;
5195 const size_t numMonitors = monitors.size();
5196 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005197 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005198 monitors.erase(monitors.begin() + i);
5199 break;
5200 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005201 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005202 if (monitors.empty()) {
5203 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005204 } else {
5205 ++it;
5206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207 }
5208}
5209
Michael Wright3dd60e22019-03-27 22:06:44 +00005210status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5211 { // acquire lock
5212 std::scoped_lock _l(mLock);
5213 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5214
5215 if (!foundDisplayId) {
5216 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5217 return BAD_VALUE;
5218 }
5219 int32_t displayId = foundDisplayId.value();
5220
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005221 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5222 mTouchStatesByDisplay.find(displayId);
5223 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005224 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5225 return BAD_VALUE;
5226 }
5227
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005228 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005229 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005230 std::optional<int32_t> foundDeviceId;
5231 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005232 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005233 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005234 foundDeviceId = state.deviceId;
5235 }
5236 }
5237 if (!foundDeviceId || !state.down) {
5238 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005239 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005240 return BAD_VALUE;
5241 }
5242 int32_t deviceId = foundDeviceId.value();
5243
5244 // Send cancel events to all the input channels we're stealing from.
5245 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005246 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005247 options.deviceId = deviceId;
5248 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005249 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005250 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005251 std::shared_ptr<InputChannel> channel =
5252 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005253 if (channel != nullptr) {
5254 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005255 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005256 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005257 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005258 canceledWindows += "]";
5259 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5260 canceledWindows.c_str());
5261
Michael Wright3dd60e22019-03-27 22:06:44 +00005262 // Then clear the current touch state so we stop dispatching to them as well.
5263 state.filterNonMonitors();
5264 }
5265 return OK;
5266}
5267
Prabir Pradhan99987712020-11-10 18:43:05 -08005268void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5269 { // acquire lock
5270 std::scoped_lock _l(mLock);
5271 if (DEBUG_FOCUS) {
5272 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5273 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5274 windowHandle != nullptr ? windowHandle->getName().c_str()
5275 : "token without window");
5276 }
5277
Vishnu Nairc519ff72021-01-21 08:23:08 -08005278 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005279 if (focusedToken != windowToken) {
5280 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5281 enabled ? "enable" : "disable");
5282 return;
5283 }
5284
5285 if (enabled == mFocusedWindowRequestedPointerCapture) {
5286 ALOGW("Ignoring request to %s Pointer Capture: "
5287 "window has %s requested pointer capture.",
5288 enabled ? "enable" : "disable", enabled ? "already" : "not");
5289 return;
5290 }
5291
5292 mFocusedWindowRequestedPointerCapture = enabled;
5293 setPointerCaptureLocked(enabled);
5294 } // release lock
5295
5296 // Wake the thread to process command entries.
5297 mLooper->wake();
5298}
5299
Michael Wright3dd60e22019-03-27 22:06:44 +00005300std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5301 const sp<IBinder>& token) {
5302 for (const auto& it : mGestureMonitorsByDisplay) {
5303 const std::vector<Monitor>& monitors = it.second;
5304 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005305 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005306 return it.first;
5307 }
5308 }
5309 }
5310 return std::nullopt;
5311}
5312
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005313std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5314 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5315 if (gesturePid.has_value()) {
5316 return gesturePid;
5317 }
5318 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5319}
5320
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005321sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005322 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005323 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005324 }
5325
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005326 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005327 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005328 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005329 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 }
5331 }
Robert Carr4e670e52018-08-15 13:26:12 -07005332
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005333 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334}
5335
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005336std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5337 sp<Connection> connection = getConnectionLocked(connectionToken);
5338 if (connection == nullptr) {
5339 return "<nullptr>";
5340 }
5341 return connection->getInputChannelName();
5342}
5343
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005344void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005345 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005346 removeByValue(mConnectionsByFd, connection);
5347}
5348
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005349void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5350 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005351 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005352 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5353 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 commandEntry->connection = connection;
5355 commandEntry->eventTime = currentTime;
5356 commandEntry->seq = seq;
5357 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005358 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005359 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360}
5361
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005362void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5363 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005365 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005367 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5368 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005370 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371}
5372
Vishnu Nairad321cd2020-08-20 16:40:21 -07005373void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5374 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005375 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5376 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005377 commandEntry->oldToken = oldToken;
5378 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005379 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005380}
5381
arthurhungf452d0b2021-01-06 00:19:52 +08005382void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5383 std::unique_ptr<CommandEntry> commandEntry =
5384 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5385 commandEntry->newToken = token;
5386 commandEntry->x = x;
5387 commandEntry->y = y;
5388 postCommandLocked(std::move(commandEntry));
5389}
5390
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005391void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5392 if (connection == nullptr) {
5393 LOG_ALWAYS_FATAL("Caller must check for nullness");
5394 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005395 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5396 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005397 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005398 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005399 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005400 return;
5401 }
5402 /**
5403 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5404 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5405 * has changed. This could cause newer entries to time out before the already dispatched
5406 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5407 * processes the events linearly. So providing information about the oldest entry seems to be
5408 * most useful.
5409 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005410 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005411 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5412 std::string reason =
5413 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005414 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005415 ns2ms(currentWait),
5416 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005417 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005418 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005419
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005420 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5421
5422 // Stop waking up for events on this connection, it is already unresponsive
5423 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005424}
5425
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005426void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5427 std::string reason =
5428 StringPrintf("%s does not have a focused window", application->getName().c_str());
5429 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005430
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005431 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5432 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5433 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005434 postCommandLocked(std::move(commandEntry));
5435}
5436
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005437void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5438 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5439 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5440 commandEntry->obscuringPackage = obscuringPackage;
5441 postCommandLocked(std::move(commandEntry));
5442}
5443
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005444void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5445 const std::string& reason) {
5446 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5447 updateLastAnrStateLocked(windowLabel, reason);
5448}
5449
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005450void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5451 const std::string& reason) {
5452 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005453 updateLastAnrStateLocked(windowLabel, reason);
5454}
5455
5456void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5457 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005459 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 struct tm tm;
5461 localtime_r(&t, &tm);
5462 char timestr[64];
5463 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005464 mLastAnrState.clear();
5465 mLastAnrState += INDENT "ANR:\n";
5466 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005467 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5468 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005469 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470}
5471
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005472void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 mLock.unlock();
5474
5475 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5476
5477 mLock.lock();
5478}
5479
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005480void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 sp<Connection> connection = commandEntry->connection;
5482
5483 if (connection->status != Connection::STATUS_ZOMBIE) {
5484 mLock.unlock();
5485
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005486 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487
5488 mLock.lock();
5489 }
5490}
5491
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005492void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005493 sp<IBinder> oldToken = commandEntry->oldToken;
5494 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005495 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005496 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005497 mLock.lock();
5498}
5499
arthurhungf452d0b2021-01-06 00:19:52 +08005500void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5501 sp<IBinder> newToken = commandEntry->newToken;
5502 mLock.unlock();
5503 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5504 mLock.lock();
5505}
5506
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005507void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005509
5510 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5511
5512 mLock.lock();
5513}
5514
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005515void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005516 mLock.unlock();
5517
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005518 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519
5520 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005521}
5522
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005523void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005524 mLock.unlock();
5525
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005526 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5527
5528 mLock.lock();
5529}
5530
5531void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5532 mLock.unlock();
5533
5534 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5535
5536 mLock.lock();
5537}
5538
5539void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5540 mLock.unlock();
5541
5542 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005543
5544 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005545}
5546
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005547void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5548 mLock.unlock();
5549
5550 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5551
5552 mLock.lock();
5553}
5554
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5556 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005557 KeyEntry& entry = *(commandEntry->keyEntry);
5558 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559
5560 mLock.unlock();
5561
Michael Wright2b3c3302018-03-02 17:19:13 +00005562 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005563 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005564 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005565 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5566 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005567 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569
5570 mLock.lock();
5571
5572 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005573 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005575 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005577 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5578 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580}
5581
chaviwfd6d3512019-03-25 13:23:49 -07005582void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5583 mLock.unlock();
5584 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5585 mLock.lock();
5586}
5587
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005588/**
5589 * Connection is responsive if it has no events in the waitQueue that are older than the
5590 * current time.
5591 */
5592static bool isConnectionResponsive(const Connection& connection) {
5593 const nsecs_t currentTime = now();
5594 for (const DispatchEntry* entry : connection.waitQueue) {
5595 if (entry->timeoutTime < currentTime) {
5596 return false;
5597 }
5598 }
5599 return true;
5600}
5601
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005602void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005604 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005606 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
5608 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005609 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005610 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005611 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005613 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005614 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005615 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005616 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5617 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005618 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005619 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005620
5621 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005622 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005623 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005624 restartEvent =
5625 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005626 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005627 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005628 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5629 handled);
5630 } else {
5631 restartEvent = false;
5632 }
5633
5634 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005635 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005636 // contents of the wait queue to have been drained, so we need to double-check
5637 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005638 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5639 if (dispatchEntryIt != connection->waitQueue.end()) {
5640 dispatchEntry = *dispatchEntryIt;
5641 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005642 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5643 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005644 if (!connection->responsive) {
5645 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005646 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005647 // The connection was unresponsive, and now it's responsive.
5648 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005649 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005650 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005651 traceWaitQueueLength(connection);
5652 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005653 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005654 traceOutboundQueueLength(connection);
5655 } else {
5656 releaseDispatchEntry(dispatchEntry);
5657 }
5658 }
5659
5660 // Start the next dispatch cycle for this connection.
5661 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662}
5663
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005664void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5665 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5666 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5667 monitorUnresponsiveCommand->pid = pid;
5668 monitorUnresponsiveCommand->reason = std::move(reason);
5669 postCommandLocked(std::move(monitorUnresponsiveCommand));
5670}
5671
5672void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5673 std::string reason) {
5674 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5675 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5676 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5677 windowUnresponsiveCommand->reason = std::move(reason);
5678 postCommandLocked(std::move(windowUnresponsiveCommand));
5679}
5680
5681void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5682 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5683 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5684 monitorResponsiveCommand->pid = pid;
5685 postCommandLocked(std::move(monitorResponsiveCommand));
5686}
5687
5688void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5689 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5690 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5691 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5692 postCommandLocked(std::move(windowResponsiveCommand));
5693}
5694
5695/**
5696 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5697 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5698 * command entry to the command queue.
5699 */
5700void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5701 std::string reason) {
5702 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5703 if (connection.monitor) {
5704 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5705 reason.c_str());
5706 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5707 if (!pid.has_value()) {
5708 ALOGE("Could not find unresponsive monitor for connection %s",
5709 connection.inputChannel->getName().c_str());
5710 return;
5711 }
5712 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5713 return;
5714 }
5715 // If not a monitor, must be a window
5716 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5717 reason.c_str());
5718 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5719}
5720
5721/**
5722 * Tell the policy that a connection has become responsive so that it can stop ANR.
5723 */
5724void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5725 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5726 if (connection.monitor) {
5727 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5728 if (!pid.has_value()) {
5729 ALOGE("Could not find responsive monitor for connection %s",
5730 connection.inputChannel->getName().c_str());
5731 return;
5732 }
5733 sendMonitorResponsiveCommandLocked(pid.value());
5734 return;
5735 }
5736 // If not a monitor, must be a window
5737 sendWindowResponsiveCommandLocked(connectionToken);
5738}
5739
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005741 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005742 KeyEntry& keyEntry, bool handled) {
5743 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005744 if (!handled) {
5745 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005746 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005747 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005748 return false;
5749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005751 // Get the fallback key state.
5752 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005753 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005754 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005755 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005756 connection->inputState.removeFallbackKey(originalKeyCode);
5757 }
5758
5759 if (handled || !dispatchEntry->hasForegroundTarget()) {
5760 // If the application handles the original key for which we previously
5761 // generated a fallback or if the window is not a foreground window,
5762 // then cancel the associated fallback key, if any.
5763 if (fallbackKeyCode != -1) {
5764 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005766 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005767 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005768 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005770 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005771 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772
5773 mLock.unlock();
5774
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005775 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005776 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777
5778 mLock.lock();
5779
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005780 // Cancel the fallback key.
5781 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005783 "application handled the original non-fallback key "
5784 "or is no longer a foreground target, "
5785 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786 options.keyCode = fallbackKeyCode;
5787 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005789 connection->inputState.removeFallbackKey(originalKeyCode);
5790 }
5791 } else {
5792 // If the application did not handle a non-fallback key, first check
5793 // that we are in a good state to perform unhandled key event processing
5794 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005795 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005796 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005798 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005799 "since this is not an initial down. "
5800 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005801 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005803 return false;
5804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005806 // Dispatch the unhandled key to the policy.
5807#if DEBUG_OUTBOUND_EVENT_DETAILS
5808 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005809 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005810 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005811#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005812 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005813
5814 mLock.unlock();
5815
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005816 bool fallback =
5817 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005818 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005819
5820 mLock.lock();
5821
5822 if (connection->status != Connection::STATUS_NORMAL) {
5823 connection->inputState.removeFallbackKey(originalKeyCode);
5824 return false;
5825 }
5826
5827 // Latch the fallback keycode for this key on an initial down.
5828 // The fallback keycode cannot change at any other point in the lifecycle.
5829 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005831 fallbackKeyCode = event.getKeyCode();
5832 } else {
5833 fallbackKeyCode = AKEYCODE_UNKNOWN;
5834 }
5835 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5836 }
5837
5838 ALOG_ASSERT(fallbackKeyCode != -1);
5839
5840 // Cancel the fallback key if the policy decides not to send it anymore.
5841 // We will continue to dispatch the key to the policy but we will no
5842 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005843 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5844 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005845#if DEBUG_OUTBOUND_EVENT_DETAILS
5846 if (fallback) {
5847 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005848 "as a fallback for %d, but on the DOWN it had requested "
5849 "to send %d instead. Fallback canceled.",
5850 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005851 } else {
5852 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005853 "but on the DOWN it had requested to send %d. "
5854 "Fallback canceled.",
5855 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005856 }
5857#endif
5858
5859 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5860 "canceling fallback, policy no longer desires it");
5861 options.keyCode = fallbackKeyCode;
5862 synthesizeCancelationEventsForConnectionLocked(connection, options);
5863
5864 fallback = false;
5865 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005866 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005867 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005868 }
5869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870
5871#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005872 {
5873 std::string msg;
5874 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5875 connection->inputState.getFallbackKeys();
5876 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005877 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005878 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005879 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005880 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 }
5882#endif
5883
5884 if (fallback) {
5885 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005886 keyEntry.eventTime = event.getEventTime();
5887 keyEntry.deviceId = event.getDeviceId();
5888 keyEntry.source = event.getSource();
5889 keyEntry.displayId = event.getDisplayId();
5890 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5891 keyEntry.keyCode = fallbackKeyCode;
5892 keyEntry.scanCode = event.getScanCode();
5893 keyEntry.metaState = event.getMetaState();
5894 keyEntry.repeatCount = event.getRepeatCount();
5895 keyEntry.downTime = event.getDownTime();
5896 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897
5898#if DEBUG_OUTBOUND_EVENT_DETAILS
5899 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005900 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005901 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005902#endif
5903 return true; // restart the event
5904 } else {
5905#if DEBUG_OUTBOUND_EVENT_DETAILS
5906 ALOGD("Unhandled key event: No fallback key.");
5907#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005908
5909 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005910 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911 }
5912 }
5913 return false;
5914}
5915
5916bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005917 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 return false;
5920}
5921
5922void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5923 mLock.unlock();
5924
Sean Stoutb4e0a592021-02-23 07:34:53 -08005925 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
5926 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927
5928 mLock.lock();
5929}
5930
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005931void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5932 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 // TODO Write some statistics about how long we spend waiting.
5934}
5935
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005936/**
5937 * Report the touch event latency to the statsd server.
5938 * Input events are reported for statistics if:
5939 * - This is a touchscreen event
5940 * - InputFilter is not enabled
5941 * - Event is not injected or synthesized
5942 *
5943 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5944 * from getting aggregated with the "old" data.
5945 */
5946void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5947 REQUIRES(mLock) {
5948 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5949 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5950 if (!reportForStatistics) {
5951 return;
5952 }
5953
5954 if (mTouchStatistics.shouldReport()) {
5955 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5956 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5957 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5958 mTouchStatistics.reset();
5959 }
5960 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5961 mTouchStatistics.addValue(latencyMicros);
5962}
5963
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964void InputDispatcher::traceInboundQueueLengthLocked() {
5965 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005966 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 }
5968}
5969
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005970void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 if (ATRACE_ENABLED()) {
5972 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005973 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005974 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 }
5976}
5977
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005978void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 if (ATRACE_ENABLED()) {
5980 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005981 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005982 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 }
5984}
5985
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005986void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005989 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990 dumpDispatchStateLocked(dump);
5991
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005992 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005993 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005994 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 }
5996}
5997
5998void InputDispatcher::monitor() {
5999 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006000 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006001 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006002 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003}
6004
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006005/**
6006 * Wake up the dispatcher and wait until it processes all events and commands.
6007 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6008 * this method can be safely called from any thread, as long as you've ensured that
6009 * the work you are interested in completing has already been queued.
6010 */
6011bool InputDispatcher::waitForIdle() {
6012 /**
6013 * Timeout should represent the longest possible time that a device might spend processing
6014 * events and commands.
6015 */
6016 constexpr std::chrono::duration TIMEOUT = 100ms;
6017 std::unique_lock lock(mLock);
6018 mLooper->wake();
6019 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6020 return result == std::cv_status::no_timeout;
6021}
6022
Vishnu Naire798b472020-07-23 13:52:21 -07006023/**
6024 * Sets focus to the window identified by the token. This must be called
6025 * after updating any input window handles.
6026 *
6027 * Params:
6028 * request.token - input channel token used to identify the window that should gain focus.
6029 * request.focusedToken - the token that the caller expects currently to be focused. If the
6030 * specified token does not match the currently focused window, this request will be dropped.
6031 * If the specified focused token matches the currently focused window, the call will succeed.
6032 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6033 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6034 * when requesting the focus change. This determines which request gets
6035 * precedence if there is a focus change request from another source such as pointer down.
6036 */
Vishnu Nair958da932020-08-21 17:12:37 -07006037void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6038 { // acquire lock
6039 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006040 std::optional<FocusResolver::FocusChanges> changes =
6041 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6042 if (changes) {
6043 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006044 }
6045 } // release lock
6046 // Wake up poll loop since it may need to make new input dispatching choices.
6047 mLooper->wake();
6048}
6049
Vishnu Nairc519ff72021-01-21 08:23:08 -08006050void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6051 if (changes.oldFocus) {
6052 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006053 if (focusedInputChannel) {
6054 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6055 "focus left window");
6056 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006057 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006058 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006059 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006060 if (changes.newFocus) {
6061 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006062 }
6063
Prabir Pradhan99987712020-11-10 18:43:05 -08006064 // If a window has pointer capture, then it must have focus. We need to ensure that this
6065 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6066 // If the window loses focus before it loses pointer capture, then the window can be in a state
6067 // where it has pointer capture but not focus, violating the contract. Therefore we must
6068 // dispatch the pointer capture event before the focus event. Since focus events are added to
6069 // the front of the queue (above), we add the pointer capture event to the front of the queue
6070 // after the focus events are added. This ensures the pointer capture event ends up at the
6071 // front.
6072 disablePointerCaptureForcedLocked();
6073
Vishnu Nairc519ff72021-01-21 08:23:08 -08006074 if (mFocusedDisplayId == changes.displayId) {
6075 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006076 }
6077}
Vishnu Nair958da932020-08-21 17:12:37 -07006078
Prabir Pradhan99987712020-11-10 18:43:05 -08006079void InputDispatcher::disablePointerCaptureForcedLocked() {
6080 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6081 return;
6082 }
6083
6084 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6085
6086 if (mFocusedWindowRequestedPointerCapture) {
6087 mFocusedWindowRequestedPointerCapture = false;
6088 setPointerCaptureLocked(false);
6089 }
6090
6091 if (!mWindowTokenWithPointerCapture) {
6092 // No need to send capture changes because no window has capture.
6093 return;
6094 }
6095
6096 if (mPendingEvent != nullptr) {
6097 // Move the pending event to the front of the queue. This will give the chance
6098 // for the pending event to be dropped if it is a captured event.
6099 mInboundQueue.push_front(mPendingEvent);
6100 mPendingEvent = nullptr;
6101 }
6102
6103 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6104 false /* hasCapture */);
6105 mInboundQueue.push_front(std::move(entry));
6106}
6107
Prabir Pradhan99987712020-11-10 18:43:05 -08006108void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6109 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6110 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6111 commandEntry->enabled = enabled;
6112 postCommandLocked(std::move(commandEntry));
6113}
6114
6115void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6116 android::inputdispatcher::CommandEntry* commandEntry) {
6117 mLock.unlock();
6118
6119 mPolicy->setPointerCapture(commandEntry->enabled);
6120
6121 mLock.lock();
6122}
6123
Garfield Tane84e6f92019-08-29 17:28:41 -07006124} // namespace android::inputdispatcher