blob: 6d405d8200c879b1094730a57023c21fd8d61c6d [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
93// Default input dispatching timeout if there is no focused application or paused window
94// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080095const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
96 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
97 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
99// Amount of time to allow for all pending events to be processed when an app switch
100// key is on the way. This is used to preempt input dispatch and drop input events
101// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Amount of time to allow for an event to be dispatched (measured since its eventTime)
105// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// 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 +0000109constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
110
111// Log a warning when an interception call takes longer than this to process.
112constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700114// Additional key latency in case a connection is still processing some motion events.
115// This will help with the case when a user touched a button that opens a new window,
116// and gives us the chance to dispatch the key to this new window.
117constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
118
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000120constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
121
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000122// Event log tags. See EventLogTags.logtags for reference
123constexpr int LOGTAG_INPUT_INTERACTION = 62000;
124constexpr int LOGTAG_INPUT_FOCUS = 62001;
125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126static inline nsecs_t now() {
127 return systemTime(SYSTEM_TIME_MONOTONIC);
128}
129
130static inline const char* toString(bool value) {
131 return value ? "true" : "false";
132}
133
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000134static inline const std::string toString(sp<IBinder> binder) {
135 if (binder == nullptr) {
136 return "<null>";
137 }
138 return StringPrintf("%p", binder.get());
139}
140
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
143 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144}
145
146static bool isValidKeyAction(int32_t action) {
147 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700148 case AKEY_EVENT_ACTION_DOWN:
149 case AKEY_EVENT_ACTION_UP:
150 return true;
151 default:
152 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153 }
154}
155
156static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800158 ALOGE("Key event has invalid action code 0x%x", action);
159 return false;
160 }
161 return true;
162}
163
Michael Wright7b159c92015-05-14 14:48:03 +0100164static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_DOWN:
167 case AMOTION_EVENT_ACTION_UP:
168 case AMOTION_EVENT_ACTION_CANCEL:
169 case AMOTION_EVENT_ACTION_MOVE:
170 case AMOTION_EVENT_ACTION_OUTSIDE:
171 case AMOTION_EVENT_ACTION_HOVER_ENTER:
172 case AMOTION_EVENT_ACTION_HOVER_MOVE:
173 case AMOTION_EVENT_ACTION_HOVER_EXIT:
174 case AMOTION_EVENT_ACTION_SCROLL:
175 return true;
176 case AMOTION_EVENT_ACTION_POINTER_DOWN:
177 case AMOTION_EVENT_ACTION_POINTER_UP: {
178 int32_t index = getMotionEventActionPointerIndex(action);
179 return index >= 0 && index < pointerCount;
180 }
181 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
182 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
183 return actionButton != 0;
184 default:
185 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 }
187}
188
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500189static int64_t millis(std::chrono::nanoseconds t) {
190 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
191}
192
Michael Wright7b159c92015-05-14 14:48:03 +0100193static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 const PointerProperties* pointerProperties) {
195 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 ALOGE("Motion event has invalid action code 0x%x", action);
197 return false;
198 }
199 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000200 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700201 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 return false;
203 }
204 BitSet32 pointerIdBits;
205 for (size_t i = 0; i < pointerCount; i++) {
206 int32_t id = pointerProperties[i].id;
207 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700208 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
209 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 return false;
211 }
212 if (pointerIdBits.hasBit(id)) {
213 ALOGE("Motion event has duplicate pointer id %d", id);
214 return false;
215 }
216 pointerIdBits.markBit(id);
217 }
218 return true;
219}
220
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000221static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000223 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
225
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000226 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 bool first = true;
228 Region::const_iterator cur = region.begin();
229 Region::const_iterator const tail = region.end();
230 while (cur != tail) {
231 if (first) {
232 first = false;
233 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800236 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 cur++;
238 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000239 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240}
241
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500242static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
243 constexpr size_t maxEntries = 50; // max events to print
244 constexpr size_t skipBegin = maxEntries / 2;
245 const size_t skipEnd = queue.size() - maxEntries / 2;
246 // skip from maxEntries / 2 ... size() - maxEntries/2
247 // only print from 0 .. skipBegin and then from skipEnd .. size()
248
249 std::string dump;
250 for (size_t i = 0; i < queue.size(); i++) {
251 const DispatchEntry& entry = *queue[i];
252 if (i >= skipBegin && i < skipEnd) {
253 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
254 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
255 continue;
256 }
257 dump.append(INDENT4);
258 dump += entry.eventEntry->getDescription();
259 dump += StringPrintf(", seq=%" PRIu32
260 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
261 entry.seq, entry.targetFlags, entry.resolvedAction,
262 ns2ms(currentTime - entry.eventEntry->eventTime));
263 if (entry.deliveryTime != 0) {
264 // This entry was delivered, so add information on how long we've been waiting
265 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
266 }
267 dump.append("\n");
268 }
269 return dump;
270}
271
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700272/**
273 * Find the entry in std::unordered_map by key, and return it.
274 * If the entry is not found, return a default constructed entry.
275 *
276 * Useful when the entries are vectors, since an empty vector will be returned
277 * if the entry is not found.
278 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
279 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700280template <typename K, typename V>
281static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700282 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700283 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800284}
285
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700286/**
287 * Find the entry in std::unordered_map by value, and remove it.
288 * If more than one entry has the same value, then all matching
289 * key-value pairs will be removed.
290 *
291 * Return true if at least one value has been removed.
292 */
293template <typename K, typename V>
294static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
295 bool removed = false;
296 for (auto it = map.begin(); it != map.end();) {
297 if (it->second == value) {
298 it = map.erase(it);
299 removed = true;
300 } else {
301 it++;
302 }
303 }
304 return removed;
305}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306
chaviwaf87b3e2019-10-01 16:59:28 -0700307static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
308 if (first == second) {
309 return true;
310 }
311
312 if (first == nullptr || second == nullptr) {
313 return false;
314 }
315
316 return first->getToken() == second->getToken();
317}
318
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000319static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
320 if (first == nullptr || second == nullptr) {
321 return false;
322 }
323 return first->applicationInfo.token != nullptr &&
324 first->applicationInfo.token == second->applicationInfo.token;
325}
326
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800327static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
328 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
329}
330
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700332 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000333 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900334 if (eventEntry->type == EventEntry::Type::MOTION) {
335 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800336 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900337 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800338 // Use identity transform for events that are not pointer events because their axes
339 // values do not represent on-screen coordinates, so they should not have any window
340 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900341 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
342 1.0f /*globalScaleFactor*/);
343 }
344 }
345
chaviw1ff3d1e2020-07-01 15:53:47 -0700346 if (inputTarget.useDefaultPointerTransform()) {
347 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700348 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700349 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000350 }
351
352 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
353 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 std::vector<PointerCoords> pointerCoords;
356 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357
358 // Use the first pointer information to normalize all other pointers. This could be any pointer
359 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700360 // uses the transform for the normalized pointer.
361 const ui::Transform& firstPointerTransform =
362 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
363 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000364
365 // Iterate through all pointers in the event to normalize against the first.
366 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
367 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
368 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370
371 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 // First, apply the current pointer's transform to update the coordinates into
373 // window space.
374 pointerCoords[pointerIndex].transform(currTransform);
375 // Next, apply the inverse transform of the normalized coordinates so the
376 // current coordinates are transformed into the normalized coordinate space.
377 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378 }
379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700380 std::unique_ptr<MotionEntry> combinedMotionEntry =
381 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
382 motionEntry.deviceId, motionEntry.source,
383 motionEntry.displayId, motionEntry.policyFlags,
384 motionEntry.action, motionEntry.actionButton,
385 motionEntry.flags, motionEntry.metaState,
386 motionEntry.buttonState, motionEntry.classification,
387 motionEntry.edgeFlags, motionEntry.xPrecision,
388 motionEntry.yPrecision, motionEntry.xCursorPosition,
389 motionEntry.yCursorPosition, motionEntry.downTime,
390 motionEntry.pointerCount, motionEntry.pointerProperties,
391 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000392
393 if (motionEntry.injectionState) {
394 combinedMotionEntry->injectionState = motionEntry.injectionState;
395 combinedMotionEntry->injectionState->refCount += 1;
396 }
397
398 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700399 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
400 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000401 return dispatchEntry;
402}
403
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700404static void addGestureMonitors(const std::vector<Monitor>& monitors,
405 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
406 float yOffset = 0) {
407 if (monitors.empty()) {
408 return;
409 }
410 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
411 for (const Monitor& monitor : monitors) {
412 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
413 }
414}
415
Garfield Tan15601662020-09-22 15:32:38 -0700416static status_t openInputChannelPair(const std::string& name,
417 std::shared_ptr<InputChannel>& serverChannel,
418 std::unique_ptr<InputChannel>& clientChannel) {
419 std::unique_ptr<InputChannel> uniqueServerChannel;
420 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
421
422 serverChannel = std::move(uniqueServerChannel);
423 return result;
424}
425
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500426template <typename T>
427static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
428 if (lhs == nullptr && rhs == nullptr) {
429 return true;
430 }
431 if (lhs == nullptr || rhs == nullptr) {
432 return false;
433 }
434 return *lhs == *rhs;
435}
436
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000437static sp<IPlatformCompatNative> getCompatService() {
438 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
439 if (service == nullptr) {
440 ALOGE("Failed to link to compat service");
441 return nullptr;
442 }
443 return interface_cast<IPlatformCompatNative>(service);
444}
445
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000446static KeyEvent createKeyEvent(const KeyEntry& entry) {
447 KeyEvent event;
448 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
449 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
450 entry.repeatCount, entry.downTime, entry.eventTime);
451 return event;
452}
453
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000454static std::optional<int32_t> findMonitorPidByToken(
455 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
456 const sp<IBinder>& token) {
457 for (const auto& it : monitorsByDisplay) {
458 const std::vector<Monitor>& monitors = it.second;
459 for (const Monitor& monitor : monitors) {
460 if (monitor.inputChannel->getConnectionToken() == token) {
461 return monitor.pid;
462 }
463 }
464 }
465 return std::nullopt;
466}
467
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468// --- InputDispatcher ---
469
Garfield Tan00f511d2019-06-12 16:55:40 -0700470InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
471 : mPolicy(policy),
472 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700473 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800474 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700475 mAppSwitchSawKeyDown(false),
476 mAppSwitchDueTime(LONG_LONG_MAX),
477 mNextUnblockedEvent(nullptr),
478 mDispatchEnabled(false),
479 mDispatchFrozen(false),
480 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800481 // mInTouchMode will be initialized by the WindowManager to the default device config.
482 // To avoid leaking stack in case that call never comes, and for tests,
483 // initialize it here anyways.
484 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100485 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000486 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800487 mFocusedWindowRequestedPointerCapture(false),
488 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000489 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800491 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492
Yi Kong9b14ac62018-07-17 13:48:38 -0700493 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494
495 policy->getDispatcherConfiguration(&mConfig);
496}
497
498InputDispatcher::~InputDispatcher() {
499 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800500 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501
502 resetKeyRepeatLocked();
503 releasePendingEventLocked();
504 drainInboundQueueLocked();
505 }
506
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700507 while (!mConnectionsByFd.empty()) {
508 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700509 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 }
511}
512
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700513status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700514 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700515 return ALREADY_EXISTS;
516 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700517 mThread = std::make_unique<InputThread>(
518 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
519 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700520}
521
522status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700523 if (mThread && mThread->isCallingThread()) {
524 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700525 return INVALID_OPERATION;
526 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700527 mThread.reset();
528 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700529}
530
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531void InputDispatcher::dispatchOnce() {
532 nsecs_t nextWakeupTime = LONG_LONG_MAX;
533 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800534 std::scoped_lock _l(mLock);
535 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536
537 // Run a dispatch loop if there are no pending commands.
538 // The dispatch loop might enqueue commands to run afterwards.
539 if (!haveCommandsLocked()) {
540 dispatchOnceInnerLocked(&nextWakeupTime);
541 }
542
543 // Run all pending commands if there are any.
544 // If any commands were run then force the next poll to wake up immediately.
545 if (runCommandsLockedInterruptible()) {
546 nextWakeupTime = LONG_LONG_MIN;
547 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800548
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700549 // If we are still waiting for ack on some events,
550 // we might have to wake up earlier to check if an app is anr'ing.
551 const nsecs_t nextAnrCheck = processAnrsLocked();
552 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
553
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800554 // We are about to enter an infinitely long sleep, because we have no commands or
555 // pending or queued events
556 if (nextWakeupTime == LONG_LONG_MAX) {
557 mDispatcherEnteredIdle.notify_all();
558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 } // release lock
560
561 // Wait for callback or timeout or wake. (make sure we round up, not down)
562 nsecs_t currentTime = now();
563 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
564 mLooper->pollOnce(timeoutMillis);
565}
566
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700567/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500568 * Raise ANR if there is no focused window.
569 * Before the ANR is raised, do a final state check:
570 * 1. The currently focused application must be the same one we are waiting for.
571 * 2. Ensure we still don't have a focused window.
572 */
573void InputDispatcher::processNoFocusedWindowAnrLocked() {
574 // Check if the application that we are waiting for is still focused.
575 std::shared_ptr<InputApplicationHandle> focusedApplication =
576 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
577 if (focusedApplication == nullptr ||
578 focusedApplication->getApplicationToken() !=
579 mAwaitedFocusedApplication->getApplicationToken()) {
580 // Unexpected because we should have reset the ANR timer when focused application changed
581 ALOGE("Waited for a focused window, but focused application has already changed to %s",
582 focusedApplication->getName().c_str());
583 return; // The focused application has changed.
584 }
585
586 const sp<InputWindowHandle>& focusedWindowHandle =
587 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
588 if (focusedWindowHandle != nullptr) {
589 return; // We now have a focused window. No need for ANR.
590 }
591 onAnrLocked(mAwaitedFocusedApplication);
592}
593
594/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700595 * Check if any of the connections' wait queues have events that are too old.
596 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
597 * Return the time at which we should wake up next.
598 */
599nsecs_t InputDispatcher::processAnrsLocked() {
600 const nsecs_t currentTime = now();
601 nsecs_t nextAnrCheck = LONG_LONG_MAX;
602 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
603 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
604 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500605 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700606 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500607 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700608 return LONG_LONG_MIN;
609 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500610 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700611 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
612 }
613 }
614
615 // Check if any connection ANRs are due
616 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
617 if (currentTime < nextAnrCheck) { // most likely scenario
618 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
619 }
620
621 // If we reached here, we have an unresponsive connection.
622 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
623 if (connection == nullptr) {
624 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
625 return nextAnrCheck;
626 }
627 connection->responsive = false;
628 // Stop waking up for this unresponsive connection
629 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000630 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700631 return LONG_LONG_MIN;
632}
633
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500634std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700635 sp<InputWindowHandle> window = getWindowHandleLocked(token);
636 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500637 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500639 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700640}
641
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
643 nsecs_t currentTime = now();
644
Jeff Browndc5992e2014-04-11 01:27:26 -0700645 // Reset the key repeat timer whenever normal dispatch is suspended while the
646 // device is in a non-interactive state. This is to ensure that we abort a key
647 // repeat if the device is just coming out of sleep.
648 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 resetKeyRepeatLocked();
650 }
651
652 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
653 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100654 if (DEBUG_FOCUS) {
655 ALOGD("Dispatch frozen. Waiting some more.");
656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 return;
658 }
659
660 // Optimize latency of app switches.
661 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
662 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
663 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
664 if (mAppSwitchDueTime < *nextWakeupTime) {
665 *nextWakeupTime = mAppSwitchDueTime;
666 }
667
668 // Ready to start a new event.
669 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700670 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700671 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 if (isAppSwitchDue) {
673 // The inbound queue is empty so the app switch key we were waiting
674 // for will never arrive. Stop waiting for it.
675 resetPendingAppSwitchLocked(false);
676 isAppSwitchDue = false;
677 }
678
679 // Synthesize a key repeat if appropriate.
680 if (mKeyRepeatState.lastKeyEntry) {
681 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
682 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
683 } else {
684 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
685 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
686 }
687 }
688 }
689
690 // Nothing to do if there is no pending event.
691 if (!mPendingEvent) {
692 return;
693 }
694 } else {
695 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700696 mPendingEvent = mInboundQueue.front();
697 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 traceInboundQueueLengthLocked();
699 }
700
701 // Poke user activity for this event.
702 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700703 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 }
706
707 // Now we have an event to dispatch.
708 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700709 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700711 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700713 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700715 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717
718 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700719 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 }
721
722 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700723 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700724 const ConfigurationChangedEntry& typedEntry =
725 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700726 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700727 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700728 break;
729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700731 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700732 const DeviceResetEntry& typedEntry =
733 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700734 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700735 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700736 break;
737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100739 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700740 std::shared_ptr<FocusEntry> typedEntry =
741 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100742 dispatchFocusLocked(currentTime, typedEntry);
743 done = true;
744 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
745 break;
746 }
747
Prabir Pradhan99987712020-11-10 18:43:05 -0800748 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
749 const auto typedEntry =
750 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
751 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
752 done = true;
753 break;
754 }
755
arthurhungb89ccb02020-12-30 16:19:01 +0800756 case EventEntry::Type::DRAG: {
757 std::shared_ptr<DragEntry> typedEntry =
758 std::static_pointer_cast<DragEntry>(mPendingEvent);
759 dispatchDragLocked(currentTime, typedEntry);
760 done = true;
761 break;
762 }
763
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700764 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700765 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700767 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 resetPendingAppSwitchLocked(true);
769 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700770 } else if (dropReason == DropReason::NOT_DROPPED) {
771 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700772 }
773 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700774 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700775 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700776 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700777 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
778 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700780 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 break;
782 }
783
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700784 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700785 std::shared_ptr<MotionEntry> motionEntry =
786 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700787 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
788 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700790 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700791 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700793 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
794 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700796 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
Chris Yef59a2f42020-10-16 12:55:26 -0700799
800 case EventEntry::Type::SENSOR: {
801 std::shared_ptr<SensorEntry> sensorEntry =
802 std::static_pointer_cast<SensorEntry>(mPendingEvent);
803 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
804 dropReason = DropReason::APP_SWITCH;
805 }
806 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
807 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
808 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
809 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
810 dropReason = DropReason::STALE;
811 }
812 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
813 done = true;
814 break;
815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700819 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700820 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
Michael Wright3a981722015-06-10 15:26:13 +0100822 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823
824 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 }
827}
828
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700829/**
830 * Return true if the events preceding this incoming motion event should be dropped
831 * Return false otherwise (the default behaviour)
832 */
833bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700834 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700835 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700836
837 // Optimize case where the current application is unresponsive and the user
838 // decides to touch a window in a different application.
839 // If the application takes too long to catch up then we drop all events preceding
840 // the touch into the other window.
841 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700842 int32_t displayId = motionEntry.displayId;
843 int32_t x = static_cast<int32_t>(
844 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
845 int32_t y = static_cast<int32_t>(
846 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
847 sp<InputWindowHandle> touchedWindowHandle =
848 findTouchedWindowAtLocked(displayId, x, y, nullptr);
849 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700850 touchedWindowHandle->getApplicationToken() !=
851 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700852 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700853 ALOGI("Pruning input queue because user touched a different application while waiting "
854 "for %s",
855 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700856 return true;
857 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700858
859 // Alternatively, maybe there's a gesture monitor that could handle this event
860 std::vector<TouchedMonitor> gestureMonitors =
861 findTouchedGestureMonitorsLocked(displayId, {});
862 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
863 sp<Connection> connection =
864 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000865 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700866 // This monitor could take more input. Drop all events preceding this
867 // event, so that gesture monitor could get a chance to receive the stream
868 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
869 "responsive gesture monitor that may handle the event",
870 mAwaitedFocusedApplication->getName().c_str());
871 return true;
872 }
873 }
874 }
875
876 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
877 // yet been processed by some connections, the dispatcher will wait for these motion
878 // events to be processed before dispatching the key event. This is because these motion events
879 // may cause a new window to be launched, which the user might expect to receive focus.
880 // To prevent waiting forever for such events, just send the key to the currently focused window
881 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
882 ALOGD("Received a new pointer down event, stop waiting for events to process and "
883 "just send the pending key event to the focused window.");
884 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700885 }
886 return false;
887}
888
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700889bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700890 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700891 mInboundQueue.push_back(std::move(newEntry));
892 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 traceInboundQueueLengthLocked();
894
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700895 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700896 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 // Optimize app switch latency.
898 // If the application takes too long to catch up then we drop all events preceding
899 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700900 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700902 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700909 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 mAppSwitchSawKeyDown = false;
911 needWake = true;
912 }
913 }
914 }
915 break;
916 }
917
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700918 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700919 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
920 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700921 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700923 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100925 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
927 break;
928 }
929 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800930 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700931 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800932 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
933 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700934 // nothing to do
935 break;
936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 }
938
939 return needWake;
940}
941
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700942void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700943 // Do not store sensor event in recent queue to avoid flooding the queue.
944 if (entry->type != EventEntry::Type::SENSOR) {
945 mRecentQueue.push_back(entry);
946 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700947 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700948 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 }
950}
951
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700953 int32_t y, TouchState* touchState,
954 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800955 bool addPortalWindows,
956 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700957 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
958 LOG_ALWAYS_FATAL(
959 "Must provide a valid touch state if adding portal windows or outside targets");
960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700962 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800963 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +0800964 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +0800965 continue;
966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 const InputWindowInfo* windowInfo = windowHandle->getInfo();
968 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100969 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970
971 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100972 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
973 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
974 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800976 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 if (portalToDisplayId != ADISPLAY_ID_NONE &&
978 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800979 if (addPortalWindows) {
980 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700981 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800982 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700983 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 // Found window.
987 return windowHandle;
988 }
989 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800990
Michael Wright44753b12020-07-08 13:48:11 +0100991 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700992 touchState->addOrUpdateWindow(windowHandle,
993 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
994 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
998 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700999 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000}
1001
Garfield Tane84e6f92019-08-29 17:28:41 -07001002std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001003 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001004 std::vector<TouchedMonitor> touchedMonitors;
1005
1006 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1007 addGestureMonitors(monitors, touchedMonitors);
1008 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1009 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1010 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1012 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001013 }
1014 return touchedMonitors;
1015}
1016
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001017void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 const char* reason;
1019 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001020 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 reason = "inbound event was dropped because the policy consumed it";
1025 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001026 case DropReason::DISABLED:
1027 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 ALOGI("Dropped event because input dispatch is disabled.");
1029 }
1030 reason = "inbound event was dropped because input dispatch is disabled";
1031 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001032 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 ALOGI("Dropped event because of pending overdue app switch.");
1034 reason = "inbound event was dropped because of pending overdue app switch";
1035 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001036 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 ALOGI("Dropped event because the current application is not responding and the user "
1038 "has started interacting with a different application.");
1039 reason = "inbound event was dropped because the current application is not responding "
1040 "and the user has started interacting with a different application";
1041 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001042 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 ALOGI("Dropped event because it is stale.");
1044 reason = "inbound event was dropped because it is stale";
1045 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001046 case DropReason::NO_POINTER_CAPTURE:
1047 ALOGI("Dropped event because there is no window with Pointer Capture.");
1048 reason = "inbound event was dropped because there is no window with Pointer Capture";
1049 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 case DropReason::NOT_DROPPED: {
1051 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 }
1055
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001056 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001057 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1059 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001062 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001063 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1064 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1066 synthesizeCancelationEventsForAllConnectionsLocked(options);
1067 } else {
1068 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1069 synthesizeCancelationEventsForAllConnectionsLocked(options);
1070 }
1071 break;
1072 }
Chris Yef59a2f42020-10-16 12:55:26 -07001073 case EventEntry::Type::SENSOR: {
1074 break;
1075 }
arthurhungb89ccb02020-12-30 16:19:01 +08001076 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1077 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001078 break;
1079 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001080 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001081 case EventEntry::Type::CONFIGURATION_CHANGED:
1082 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001083 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001084 break;
1085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 }
1087}
1088
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001089static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1091 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092}
1093
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001094bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1095 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1096 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1097 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098}
1099
1100bool InputDispatcher::isAppSwitchPendingLocked() {
1101 return mAppSwitchDueTime != LONG_LONG_MAX;
1102}
1103
1104void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1105 mAppSwitchDueTime = LONG_LONG_MAX;
1106
1107#if DEBUG_APP_SWITCH
1108 if (handled) {
1109 ALOGD("App switch has arrived.");
1110 } else {
1111 ALOGD("App switch was abandoned.");
1112 }
1113#endif
1114}
1115
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001117 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118}
1119
1120bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001121 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 return false;
1123 }
1124
1125 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001126 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001127 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001129 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130
1131 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001132 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 return true;
1134}
1135
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001136void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1137 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138}
1139
1140void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001141 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001142 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001143 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 releaseInboundEventLocked(entry);
1145 }
1146 traceInboundQueueLengthLocked();
1147}
1148
1149void InputDispatcher::releasePendingEventLocked() {
1150 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001152 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
1154}
1155
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001156void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001158 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159#if DEBUG_DISPATCH_CYCLE
1160 ALOGD("Injected inbound event was dropped.");
1161#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 }
1164 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001165 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
1167 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168}
1169
1170void InputDispatcher::resetKeyRepeatLocked() {
1171 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001172 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 }
1174}
1175
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001176std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1177 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178
Michael Wright2e732952014-09-24 13:26:59 -07001179 uint32_t policyFlags = entry->policyFlags &
1180 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001182 std::shared_ptr<KeyEntry> newEntry =
1183 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1184 entry->source, entry->displayId, policyFlags, entry->action,
1185 entry->flags, entry->keyCode, entry->scanCode,
1186 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 newEntry->syntheticRepeat = true;
1189 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001191 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192}
1193
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198#endif
1199
1200 // Reset key repeating in case a keyboard device was added or removed or something.
1201 resetKeyRepeatLocked();
1202
1203 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001204 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1205 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001206 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001207 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 return true;
1209}
1210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001211bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1212 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001214 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1215 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216#endif
1217
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001218 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001219 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 synthesizeCancelationEventsForAllConnectionsLocked(options);
1221 return true;
1222}
1223
Vishnu Nairad321cd2020-08-20 16:40:21 -07001224void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001225 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001226 if (mPendingEvent != nullptr) {
1227 // Move the pending event to the front of the queue. This will give the chance
1228 // for the pending event to get dispatched to the newly focused window
1229 mInboundQueue.push_front(mPendingEvent);
1230 mPendingEvent = nullptr;
1231 }
1232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001233 std::unique_ptr<FocusEntry> focusEntry =
1234 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1235 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001236
1237 // This event should go to the front of the queue, but behind all other focus events
1238 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001239 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001240 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 [](const std::shared_ptr<EventEntry>& event) {
1242 return event->type == EventEntry::Type::FOCUS;
1243 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001244
1245 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001247}
1248
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001250 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001251 if (channel == nullptr) {
1252 return; // Window has gone away
1253 }
1254 InputTarget target;
1255 target.inputChannel = channel;
1256 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1257 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001258 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1259 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001260 std::string reason = std::string("reason=").append(entry->reason);
1261 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001262 dispatchEventLocked(currentTime, entry, {target});
1263}
1264
Prabir Pradhan99987712020-11-10 18:43:05 -08001265void InputDispatcher::dispatchPointerCaptureChangedLocked(
1266 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1267 DropReason& dropReason) {
1268 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001269 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1270 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1271 }
1272 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001273 // Pointer capture was already forcefully disabled because of focus change.
1274 dropReason = DropReason::NOT_DROPPED;
1275 return;
1276 }
1277
1278 // Set drop reason for early returns
1279 dropReason = DropReason::NO_POINTER_CAPTURE;
1280
1281 sp<IBinder> token;
1282 if (entry->pointerCaptureEnabled) {
1283 // Enable Pointer Capture
1284 if (!mFocusedWindowRequestedPointerCapture) {
1285 // This can happen if a window requests capture and immediately releases capture.
1286 ALOGW("No window requested Pointer Capture.");
1287 return;
1288 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001289 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001290 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1291 mWindowTokenWithPointerCapture = token;
1292 } else {
1293 // Disable Pointer Capture
1294 token = mWindowTokenWithPointerCapture;
1295 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001296 if (mFocusedWindowRequestedPointerCapture) {
1297 mFocusedWindowRequestedPointerCapture = false;
1298 setPointerCaptureLocked(false);
1299 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001300 }
1301
1302 auto channel = getInputChannelLocked(token);
1303 if (channel == nullptr) {
1304 // Window has gone away, clean up Pointer Capture state.
1305 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001306 if (mFocusedWindowRequestedPointerCapture) {
1307 mFocusedWindowRequestedPointerCapture = false;
1308 setPointerCaptureLocked(false);
1309 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001310 return;
1311 }
1312 InputTarget target;
1313 target.inputChannel = channel;
1314 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1315 entry->dispatchInProgress = true;
1316 dispatchEventLocked(currentTime, entry, {target});
1317
1318 dropReason = DropReason::NOT_DROPPED;
1319}
1320
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001321bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001324 if (!entry->dispatchInProgress) {
1325 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1326 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1327 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1328 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001329 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 // We have seen two identical key downs in a row which indicates that the device
1331 // driver is automatically generating key repeats itself. We take note of the
1332 // repeat here, but we disable our own next key repeat timer since it is clear that
1333 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001334 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1335 // Make sure we don't get key down from a different device. If a different
1336 // device Id has same key pressed down, the new device Id will replace the
1337 // current one to hold the key repeat with repeat count reset.
1338 // In the future when got a KEY_UP on the device id, drop it and do not
1339 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1341 resetKeyRepeatLocked();
1342 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1343 } else {
1344 // Not a repeat. Save key down state in case we do see a repeat later.
1345 resetKeyRepeatLocked();
1346 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1347 }
1348 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001349 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1350 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001351 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001352#if DEBUG_INBOUND_EVENT_DETAILS
1353 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1354#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001355 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 resetKeyRepeatLocked();
1357 }
1358
1359 if (entry->repeatCount == 1) {
1360 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1361 } else {
1362 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1363 }
1364
1365 entry->dispatchInProgress = true;
1366
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001367 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 }
1369
1370 // Handle case where the policy asked us to try again later last time.
1371 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1372 if (currentTime < entry->interceptKeyWakeupTime) {
1373 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1374 *nextWakeupTime = entry->interceptKeyWakeupTime;
1375 }
1376 return false; // wait until next wakeup
1377 }
1378 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1379 entry->interceptKeyWakeupTime = 0;
1380 }
1381
1382 // Give the policy a chance to intercept the key.
1383 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1384 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001385 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001386 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001387 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001388 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001389 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001391 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 return false; // wait for the command to run
1393 } else {
1394 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1395 }
1396 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001397 if (*dropReason == DropReason::NOT_DROPPED) {
1398 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 }
1400 }
1401
1402 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001403 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001404 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001405 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1406 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001407 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 return true;
1409 }
1410
1411 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001412 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001413 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001414 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001415 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 return false;
1417 }
1418
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001419 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001420 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 return true;
1422 }
1423
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001424 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001425 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426
1427 // Dispatch the key.
1428 dispatchEventLocked(currentTime, entry, inputTargets);
1429 return true;
1430}
1431
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001432void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001434 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1436 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001437 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1438 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1439 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440#endif
1441}
1442
Chris Yef59a2f42020-10-16 12:55:26 -07001443void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1444 mLock.unlock();
1445
1446 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1447 if (entry->accuracyChanged) {
1448 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1449 }
1450 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1451 entry->hwTimestamp, entry->values);
1452 mLock.lock();
1453}
1454
1455void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1456 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1457#if DEBUG_OUTBOUND_EVENT_DETAILS
1458 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1459 "source=0x%x, sensorType=%s",
1460 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001461 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001462#endif
1463 std::unique_ptr<CommandEntry> commandEntry =
1464 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1465 commandEntry->sensorEntry = entry;
1466 postCommandLocked(std::move(commandEntry));
1467}
1468
1469bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1470#if DEBUG_OUTBOUND_EVENT_DETAILS
1471 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1472 NamedEnum::string(sensorType).c_str());
1473#endif
1474 { // acquire lock
1475 std::scoped_lock _l(mLock);
1476
1477 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1478 std::shared_ptr<EventEntry> entry = *it;
1479 if (entry->type == EventEntry::Type::SENSOR) {
1480 it = mInboundQueue.erase(it);
1481 releaseInboundEventLocked(entry);
1482 }
1483 }
1484 }
1485 return true;
1486}
1487
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001488bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001489 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001490 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001492 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 entry->dispatchInProgress = true;
1494
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001495 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497
1498 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001499 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001500 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001501 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1502 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 return true;
1504 }
1505
1506 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1507
1508 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001509 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510
1511 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001512 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 if (isPointerEvent) {
1514 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001515 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001516 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001517 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 } else {
1519 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001520 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001521 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001523 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 return false;
1525 }
1526
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001528 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001529 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1530 return true;
1531 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001533 CancelationOptions::Mode mode(isPointerEvent
1534 ? CancelationOptions::CANCEL_POINTER_EVENTS
1535 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1536 CancelationOptions options(mode, "input event injection failed");
1537 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 return true;
1539 }
1540
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001541 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001542 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001544 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001545 std::unordered_map<int32_t, TouchState>::iterator it =
1546 mTouchStatesByDisplay.find(entry->displayId);
1547 if (it != mTouchStatesByDisplay.end()) {
1548 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001549 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001550 // The event has gone through these portal windows, so we add monitoring targets of
1551 // the corresponding displays as well.
1552 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001553 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001554 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001555 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001556 }
1557 }
1558 }
1559 }
1560
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 // Dispatch the motion.
1562 if (conflictingPointerActions) {
1563 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 synthesizeCancelationEventsForAllConnectionsLocked(options);
1566 }
1567 dispatchEventLocked(currentTime, entry, inputTargets);
1568 return true;
1569}
1570
arthurhungb89ccb02020-12-30 16:19:01 +08001571void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1572 bool isExiting, const MotionEntry& motionEntry) {
1573 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1574 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1575 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1576 PointerCoords pointerCoords;
1577 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1578 pointerCoords.transform(windowHandle->getInfo()->transform);
1579
1580 std::unique_ptr<DragEntry> dragEntry =
1581 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1582 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1583 pointerCoords.getY());
1584
1585 enqueueInboundEventLocked(std::move(dragEntry));
1586}
1587
1588void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1589 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1590 if (channel == nullptr) {
1591 return; // Window has gone away
1592 }
1593 InputTarget target;
1594 target.inputChannel = channel;
1595 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1596 entry->dispatchInProgress = true;
1597 dispatchEventLocked(currentTime, entry, {target});
1598}
1599
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001600void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001602 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001603 ", policyFlags=0x%x, "
1604 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1605 "metaState=0x%x, buttonState=0x%x,"
1606 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001607 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1608 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1609 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001613 "x=%f, y=%f, pressure=%f, size=%f, "
1614 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1615 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001616 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1617 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1618 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1619 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1620 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1621 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1622 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1623 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1624 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1625 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 }
1627#endif
1628}
1629
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001630void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1631 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001632 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001633 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634#if DEBUG_DISPATCH_CYCLE
1635 ALOGD("dispatchEventToCurrentInputTargets");
1636#endif
1637
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001638 updateInteractionTokensLocked(*eventEntry, inputTargets);
1639
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1641
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001642 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001644 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001645 sp<Connection> connection =
1646 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001647 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001648 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001650 if (DEBUG_FOCUS) {
1651 ALOGD("Dropping event delivery to target with channel '%s' because it "
1652 "is no longer registered with the input dispatcher.",
1653 inputTarget.inputChannel->getName().c_str());
1654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 }
1656 }
1657}
1658
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001659void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1660 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1661 // If the policy decides to close the app, we will get a channel removal event via
1662 // unregisterInputChannel, and will clean up the connection that way. We are already not
1663 // sending new pointers to the connection when it blocked, but focused events will continue to
1664 // pile up.
1665 ALOGW("Canceling events for %s because it is unresponsive",
1666 connection->inputChannel->getName().c_str());
1667 if (connection->status == Connection::STATUS_NORMAL) {
1668 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1669 "application not responding");
1670 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 }
1672}
1673
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001674void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001675 if (DEBUG_FOCUS) {
1676 ALOGD("Resetting ANR timeouts.");
1677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678
1679 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001680 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001681 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682}
1683
Tiger Huang721e26f2018-07-24 22:26:19 +08001684/**
1685 * Get the display id that the given event should go to. If this event specifies a valid display id,
1686 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1687 * Focused display is the display that the user most recently interacted with.
1688 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001689int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001690 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001691 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001692 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001693 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1694 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001695 break;
1696 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001697 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001698 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1699 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001700 break;
1701 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001702 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001703 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001704 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001705 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001706 case EventEntry::Type::SENSOR:
1707 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001708 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001709 return ADISPLAY_ID_NONE;
1710 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001711 }
1712 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1713}
1714
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001715bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1716 const char* focusedWindowName) {
1717 if (mAnrTracker.empty()) {
1718 // already processed all events that we waited for
1719 mKeyIsWaitingForEventsTimeout = std::nullopt;
1720 return false;
1721 }
1722
1723 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1724 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001725 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001726 mKeyIsWaitingForEventsTimeout = currentTime +
1727 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1728 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001729 return true;
1730 }
1731
1732 // We still have pending events, and already started the timer
1733 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1734 return true; // Still waiting
1735 }
1736
1737 // Waited too long, and some connection still hasn't processed all motions
1738 // Just send the key to the focused window
1739 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1740 focusedWindowName);
1741 mKeyIsWaitingForEventsTimeout = std::nullopt;
1742 return false;
1743}
1744
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001745InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1746 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1747 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001748 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
Tiger Huang721e26f2018-07-24 22:26:19 +08001750 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001751 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001752 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001753 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1754
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 // If there is no currently focused window and no focused application
1756 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1758 ALOGI("Dropping %s event because there is no focused window or focused application in "
1759 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001760 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001761 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 }
1763
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001764 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1765 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1766 // start interacting with another application via touch (app switch). This code can be removed
1767 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1768 // an app is expected to have a focused window.
1769 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1770 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1771 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001772 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1773 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1774 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001775 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001776 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001777 ALOGW("Waiting because no window has focus but %s may eventually add a "
1778 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001779 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001780 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001781 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001782 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1783 // Already raised ANR. Drop the event
1784 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001785 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787 } else {
1788 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001789 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001790 }
1791 }
1792
1793 // we have a valid, non-null focused window
1794 resetNoFocusedWindowTimeoutLocked();
1795
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001797 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001801 if (focusedWindowHandle->getInfo()->paused) {
1802 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001803 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001804 }
1805
1806 // If the event is a key event, then we must wait for all previous events to
1807 // complete before delivering it because previous events may have the
1808 // side-effect of transferring focus to a different window and we want to
1809 // ensure that the following keys are sent to the new window.
1810 //
1811 // Suppose the user touches a button in a window then immediately presses "A".
1812 // If the button causes a pop-up window to appear then we want to ensure that
1813 // the "A" key is delivered to the new pop-up window. This is because users
1814 // often anticipate pending UI changes when typing on a keyboard.
1815 // To obtain this behavior, we must serialize key events with respect to all
1816 // prior input events.
1817 if (entry.type == EventEntry::Type::KEY) {
1818 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1819 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001820 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 }
1823
1824 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001825 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001826 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1827 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828
1829 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831}
1832
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833/**
1834 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1835 * that are currently unresponsive.
1836 */
1837std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1838 const std::vector<TouchedMonitor>& monitors) const {
1839 std::vector<TouchedMonitor> responsiveMonitors;
1840 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1841 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1842 sp<Connection> connection = getConnectionLocked(
1843 monitor.monitor.inputChannel->getConnectionToken());
1844 if (connection == nullptr) {
1845 ALOGE("Could not find connection for monitor %s",
1846 monitor.monitor.inputChannel->getName().c_str());
1847 return false;
1848 }
1849 if (!connection->responsive) {
1850 ALOGW("Unresponsive monitor %s will not get the new gesture",
1851 connection->inputChannel->getName().c_str());
1852 return false;
1853 }
1854 return true;
1855 });
1856 return responsiveMonitors;
1857}
1858
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001859InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1860 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1861 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001862 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 enum InjectionPermission {
1864 INJECTION_PERMISSION_UNKNOWN,
1865 INJECTION_PERMISSION_GRANTED,
1866 INJECTION_PERMISSION_DENIED
1867 };
1868
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 // For security reasons, we defer updating the touch state until we are sure that
1870 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001871 int32_t displayId = entry.displayId;
1872 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1874
1875 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001878 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1879 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001881 // Copy current touch state into tempTouchState.
1882 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1883 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001884 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001885 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001886 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1887 mTouchStatesByDisplay.find(displayId);
1888 if (oldStateIt != mTouchStatesByDisplay.end()) {
1889 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001890 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001891 }
1892
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001893 bool isSplit = tempTouchState.split;
1894 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1895 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1896 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001897 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1898 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1899 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1900 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1901 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001902 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 bool wrongDevice = false;
1904 if (newGesture) {
1905 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001906 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001907 ALOGI("Dropping event because a pointer for a different device is already down "
1908 "in display %" PRId32,
1909 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001910 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001911 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 switchedDevice = false;
1913 wrongDevice = true;
1914 goto Failed;
1915 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001916 tempTouchState.reset();
1917 tempTouchState.down = down;
1918 tempTouchState.deviceId = entry.deviceId;
1919 tempTouchState.source = entry.source;
1920 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001922 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001923 ALOGI("Dropping move event because a pointer for a different device is already active "
1924 "in display %" PRId32,
1925 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001926 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001928 switchedDevice = false;
1929 wrongDevice = true;
1930 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 }
1932
1933 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1934 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1935
Garfield Tan00f511d2019-06-12 16:55:40 -07001936 int32_t x;
1937 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001939 // Always dispatch mouse events to cursor position.
1940 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001941 x = int32_t(entry.xCursorPosition);
1942 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001943 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001944 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1945 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001946 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001947 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001948 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001949 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1950 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001951
1952 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001953 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001954 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001957 if (newTouchedWindowHandle != nullptr &&
1958 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001959 // New window supports splitting, but we should never split mouse events.
1960 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 } else if (isSplit) {
1962 // New window does not support splitting but we have already split events.
1963 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001964 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
1966
1967 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001968 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001970 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001971 }
1972
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001973 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1974 ALOGI("Not sending touch event to %s because it is paused",
1975 newTouchedWindowHandle->getName().c_str());
1976 newTouchedWindowHandle = nullptr;
1977 }
1978
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001979 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001980 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001981 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1982 if (!isResponsive) {
1983 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1985 newTouchedWindowHandle = nullptr;
1986 }
1987 }
1988
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001989 // Drop events that can't be trusted due to occlusion
1990 if (newTouchedWindowHandle != nullptr &&
1991 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1992 TouchOcclusionInfo occlusionInfo =
1993 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001994 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001995 if (DEBUG_TOUCH_OCCLUSION) {
1996 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1997 for (const auto& log : occlusionInfo.debugInfo) {
1998 ALOGD("%s", log.c_str());
1999 }
2000 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002001 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2002 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2003 ALOGW("Dropping untrusted touch event due to %s/%d",
2004 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2005 newTouchedWindowHandle = nullptr;
2006 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002007 }
2008 }
2009
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002010 // Also don't send the new touch event to unresponsive gesture monitors
2011 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2012
Michael Wright3dd60e22019-03-27 22:06:44 +00002013 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2014 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002015 "(%d, %d) in display %" PRId32 ".",
2016 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002017 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002018 goto Failed;
2019 }
2020
2021 if (newTouchedWindowHandle != nullptr) {
2022 // Set target flags.
2023 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2024 if (isSplit) {
2025 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002027 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2028 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2029 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2030 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2031 }
2032
2033 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002034 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2035 newHoverWindowHandle = nullptr;
2036 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002037 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002038 }
2039
2040 // Update the temporary touch state.
2041 BitSet32 pointerIds;
2042 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002043 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002044 pointerIds.markBit(pointerId);
2045 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002046 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002049 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 } else {
2051 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2052
2053 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002054 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002055 if (DEBUG_FOCUS) {
2056 ALOGD("Dropping event because the pointer is not down or we previously "
2057 "dropped the pointer down event in display %" PRId32,
2058 displayId);
2059 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002060 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 goto Failed;
2062 }
2063
arthurhung6d4bed92021-03-17 11:59:33 +08002064 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002065
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002067 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002068 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002069 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2070 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
2072 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002073 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002074 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002075 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2076 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002077 if (DEBUG_FOCUS) {
2078 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2079 oldTouchedWindowHandle->getName().c_str(),
2080 newTouchedWindowHandle->getName().c_str(), displayId);
2081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002083 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2084 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2085 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
2087 // Make a slippery entrance into the new window.
2088 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2089 isSplit = true;
2090 }
2091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 int32_t targetFlags =
2093 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 if (isSplit) {
2095 targetFlags |= InputTarget::FLAG_SPLIT;
2096 }
2097 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2098 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002099 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2100 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102
2103 BitSet32 pointerIds;
2104 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002105 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002107 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 }
2109 }
2110 }
2111
2112 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002113 // Let the previous window know that the hover sequence is over, unless we already did it
2114 // when dispatching it as is to newTouchedWindowHandle.
2115 if (mLastHoverWindowHandle != nullptr &&
2116 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2117 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118#if DEBUG_HOVER
2119 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002120 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2123 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
2125
Garfield Tandf26e862020-07-01 20:18:19 -07002126 // Let the new window know that the hover sequence is starting, unless we already did it
2127 // when dispatching it as is to newTouchedWindowHandle.
2128 if (newHoverWindowHandle != nullptr &&
2129 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2130 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131#if DEBUG_HOVER
2132 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002133 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002135 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2136 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2137 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
2139 }
2140
2141 // Check permission to inject into all touched foreground windows and ensure there
2142 // is at least one touched foreground window.
2143 {
2144 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002145 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2147 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002148 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002149 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 injectionPermission = INJECTION_PERMISSION_DENIED;
2151 goto Failed;
2152 }
2153 }
2154 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002156 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002157 ALOGI("Dropping event because there is no touched foreground window in display "
2158 "%" PRId32 " or gesture monitor to receive it.",
2159 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002160 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 goto Failed;
2162 }
2163
2164 // Permission granted to injection into all touched foreground windows.
2165 injectionPermission = INJECTION_PERMISSION_GRANTED;
2166 }
2167
2168 // Check whether windows listening for outside touches are owned by the same UID. If it is
2169 // set the policy flag that we will not reveal coordinate information to this window.
2170 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2171 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002172 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002173 if (foregroundWindowHandle) {
2174 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002175 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002176 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2177 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2178 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002179 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2180 InputTarget::FLAG_ZERO_COORDS,
2181 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
2184 }
2185 }
2186 }
2187
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 // If this is the first pointer going down and the touched window has a wallpaper
2189 // then also add the touched wallpaper windows so they are locked in for the duration
2190 // of the touch gesture.
2191 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2192 // engine only supports touch events. We would need to add a mechanism similar
2193 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2194 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2195 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002196 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002197 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002198 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002199 getWindowHandlesLocked(displayId);
2200 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002202 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002203 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002205 .addOrUpdateWindow(windowHandle,
2206 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2207 InputTarget::
2208 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2209 InputTarget::FLAG_DISPATCH_AS_IS,
2210 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212 }
2213 }
2214 }
2215
2216 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002217 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002219 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002221 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
2223
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002224 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002225 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002226 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002227 }
2228
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 // Drop the outside or hover touch windows since we will not care about them
2230 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002231 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232
2233Failed:
2234 // Check injection permission once and for all.
2235 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002236 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 injectionPermission = INJECTION_PERMISSION_GRANTED;
2238 } else {
2239 injectionPermission = INJECTION_PERMISSION_DENIED;
2240 }
2241 }
2242
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002243 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2244 return injectionResult;
2245 }
2246
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002248 if (!wrongDevice) {
2249 if (switchedDevice) {
2250 if (DEBUG_FOCUS) {
2251 ALOGD("Conflicting pointer actions: Switched to a different device.");
2252 }
2253 *outConflictingPointerActions = true;
2254 }
2255
2256 if (isHoverAction) {
2257 // Started hovering, therefore no longer down.
2258 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002259 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002260 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2261 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 *outConflictingPointerActions = true;
2264 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002265 tempTouchState.reset();
2266 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2267 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2268 tempTouchState.deviceId = entry.deviceId;
2269 tempTouchState.source = entry.source;
2270 tempTouchState.displayId = displayId;
2271 }
2272 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2273 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2274 // All pointers up or canceled.
2275 tempTouchState.reset();
2276 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2277 // First pointer went down.
2278 if (oldState && oldState->down) {
2279 if (DEBUG_FOCUS) {
2280 ALOGD("Conflicting pointer actions: Down received while already down.");
2281 }
2282 *outConflictingPointerActions = true;
2283 }
2284 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2285 // One pointer went up.
2286 if (isSplit) {
2287 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2288 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002290 for (size_t i = 0; i < tempTouchState.windows.size();) {
2291 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2292 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2293 touchedWindow.pointerIds.clearBit(pointerId);
2294 if (touchedWindow.pointerIds.isEmpty()) {
2295 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2296 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002299 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002301 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002302 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002303
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002304 // Save changes unless the action was scroll in which case the temporary touch
2305 // state was only valid for this one action.
2306 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2307 if (tempTouchState.displayId >= 0) {
2308 mTouchStatesByDisplay[displayId] = tempTouchState;
2309 } else {
2310 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002314 // Update hover state.
2315 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 return injectionResult;
2319}
2320
arthurhung6d4bed92021-03-17 11:59:33 +08002321void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2322 const sp<InputWindowHandle> dropWindow =
2323 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2324 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2325 true /*ignoreDragWindow*/);
2326 if (dropWindow) {
2327 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2328 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002329 } else {
2330 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002331 }
2332 mDragState.reset();
2333}
2334
2335void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2336 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002337 return;
2338 }
2339
arthurhung6d4bed92021-03-17 11:59:33 +08002340 if (!mDragState->isStartDrag) {
2341 mDragState->isStartDrag = true;
2342 mDragState->isStylusButtonDownAtStart =
2343 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2344 }
2345
arthurhungb89ccb02020-12-30 16:19:01 +08002346 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2347 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2348 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2349 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002350 // Handle the special case : stylus button no longer pressed.
2351 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2352 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2353 finishDragAndDrop(entry.displayId, x, y);
2354 return;
2355 }
2356
arthurhungb89ccb02020-12-30 16:19:01 +08002357 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002358 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002359 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2360 true /*ignoreDragWindow*/);
2361 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002362 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2363 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2364 if (mDragState->dragHoverWindowHandle != nullptr) {
2365 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2366 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002367 }
arthurhung6d4bed92021-03-17 11:59:33 +08002368 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002369 }
2370 // enqueue drag location if needed.
2371 if (hoverWindowHandle != nullptr) {
2372 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2373 }
arthurhung6d4bed92021-03-17 11:59:33 +08002374 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2375 finishDragAndDrop(entry.displayId, x, y);
2376 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002377 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002378 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002379 }
2380}
2381
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 int32_t targetFlags, BitSet32 pointerIds,
2384 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002385 std::vector<InputTarget>::iterator it =
2386 std::find_if(inputTargets.begin(), inputTargets.end(),
2387 [&windowHandle](const InputTarget& inputTarget) {
2388 return inputTarget.inputChannel->getConnectionToken() ==
2389 windowHandle->getToken();
2390 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002391
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002392 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002393
2394 if (it == inputTargets.end()) {
2395 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002396 std::shared_ptr<InputChannel> inputChannel =
2397 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002398 if (inputChannel == nullptr) {
2399 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2400 return;
2401 }
2402 inputTarget.inputChannel = inputChannel;
2403 inputTarget.flags = targetFlags;
2404 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2405 inputTargets.push_back(inputTarget);
2406 it = inputTargets.end() - 1;
2407 }
2408
2409 ALOG_ASSERT(it->flags == targetFlags);
2410 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2411
chaviw1ff3d1e2020-07-01 15:53:47 -07002412 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413}
2414
Michael Wright3dd60e22019-03-27 22:06:44 +00002415void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002416 int32_t displayId, float xOffset,
2417 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002418 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2419 mGlobalMonitorsByDisplay.find(displayId);
2420
2421 if (it != mGlobalMonitorsByDisplay.end()) {
2422 const std::vector<Monitor>& monitors = it->second;
2423 for (const Monitor& monitor : monitors) {
2424 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 }
2427}
2428
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2430 float yOffset,
2431 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002432 InputTarget target;
2433 target.inputChannel = monitor.inputChannel;
2434 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002435 ui::Transform t;
2436 t.set(xOffset, yOffset);
2437 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002438 inputTargets.push_back(target);
2439}
2440
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002442 const InjectionState* injectionState) {
2443 if (injectionState &&
2444 (windowHandle == nullptr ||
2445 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2446 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002447 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002449 "owned by uid %d",
2450 injectionState->injectorPid, injectionState->injectorUid,
2451 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 } else {
2453 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002454 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 }
2456 return false;
2457 }
2458 return true;
2459}
2460
Robert Carrc9bf1d32020-04-13 17:21:08 -07002461/**
2462 * Indicate whether one window handle should be considered as obscuring
2463 * another window handle. We only check a few preconditions. Actually
2464 * checking the bounds is left to the caller.
2465 */
2466static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2467 const sp<InputWindowHandle>& otherHandle) {
2468 // Compare by token so cloned layers aren't counted
2469 if (haveSameToken(windowHandle, otherHandle)) {
2470 return false;
2471 }
2472 auto info = windowHandle->getInfo();
2473 auto otherInfo = otherHandle->getInfo();
2474 if (!otherInfo->visible) {
2475 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002476 } else if (otherInfo->alpha == 0 &&
2477 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2478 // Those act as if they were invisible, so we don't need to flag them.
2479 // We do want to potentially flag touchable windows even if they have 0
2480 // opacity, since they can consume touches and alter the effects of the
2481 // user interaction (eg. apps that rely on
2482 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2483 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2484 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002485 } else if (info->ownerUid == otherInfo->ownerUid) {
2486 // If ownerUid is the same we don't generate occlusion events as there
2487 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002488 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002489 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002490 return false;
2491 } else if (otherInfo->displayId != info->displayId) {
2492 return false;
2493 }
2494 return true;
2495}
2496
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002497/**
2498 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2499 * untrusted, one should check:
2500 *
2501 * 1. If result.hasBlockingOcclusion is true.
2502 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2503 * BLOCK_UNTRUSTED.
2504 *
2505 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2506 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2507 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2508 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2509 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2510 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2511 *
2512 * If neither of those is true, then it means the touch can be allowed.
2513 */
2514InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2515 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002516 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2517 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002518 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2519 TouchOcclusionInfo info;
2520 info.hasBlockingOcclusion = false;
2521 info.obscuringOpacity = 0;
2522 info.obscuringUid = -1;
2523 std::map<int32_t, float> opacityByUid;
2524 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2525 if (windowHandle == otherHandle) {
2526 break; // All future windows are below us. Exit early.
2527 }
2528 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002529 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2530 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002531 if (DEBUG_TOUCH_OCCLUSION) {
2532 info.debugInfo.push_back(
2533 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2534 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002535 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2536 // we perform the checks below to see if the touch can be propagated or not based on the
2537 // window's touch occlusion mode
2538 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2539 info.hasBlockingOcclusion = true;
2540 info.obscuringUid = otherInfo->ownerUid;
2541 info.obscuringPackage = otherInfo->packageName;
2542 break;
2543 }
2544 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2545 uint32_t uid = otherInfo->ownerUid;
2546 float opacity =
2547 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2548 // Given windows A and B:
2549 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2550 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2551 opacityByUid[uid] = opacity;
2552 if (opacity > info.obscuringOpacity) {
2553 info.obscuringOpacity = opacity;
2554 info.obscuringUid = uid;
2555 info.obscuringPackage = otherInfo->packageName;
2556 }
2557 }
2558 }
2559 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002560 if (DEBUG_TOUCH_OCCLUSION) {
2561 info.debugInfo.push_back(
2562 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2563 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002564 return info;
2565}
2566
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002567std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2568 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002569 return StringPrintf(INDENT2
2570 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2571 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2572 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2573 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002574 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002575 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002576 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002577 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2578 info->frameTop, info->frameRight, info->frameBottom,
2579 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002580 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2581 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2582 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002583}
2584
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002585bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2586 if (occlusionInfo.hasBlockingOcclusion) {
2587 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2588 occlusionInfo.obscuringUid);
2589 return false;
2590 }
2591 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2592 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2593 "%.2f, maximum allowed = %.2f)",
2594 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2595 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2596 return false;
2597 }
2598 return true;
2599}
2600
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002601bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2602 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002604 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002605 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002606 if (windowHandle == otherHandle) {
2607 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002610 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002611 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 return true;
2613 }
2614 }
2615 return false;
2616}
2617
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002618bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2619 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002620 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002621 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002622 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002623 if (windowHandle == otherHandle) {
2624 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002625 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002626 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002627 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002628 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002629 return true;
2630 }
2631 }
2632 return false;
2633}
2634
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002635std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002636 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002638 if (applicationHandle != nullptr) {
2639 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002640 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 } else {
2642 return applicationHandle->getName();
2643 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002644 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002645 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002647 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 }
2649}
2650
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002651void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002652 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002653 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2654 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002655 // Focus or pointer capture changed events are passed to apps, but do not represent user
2656 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002657 return;
2658 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002659 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002660 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002661 if (focusedWindowHandle != nullptr) {
2662 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002663 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002665 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666#endif
2667 return;
2668 }
2669 }
2670
2671 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002672 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002673 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002674 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2675 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002676 return;
2677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002679 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002680 eventType = USER_ACTIVITY_EVENT_TOUCH;
2681 }
2682 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002684 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002685 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2686 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002687 return;
2688 }
2689 eventType = USER_ACTIVITY_EVENT_BUTTON;
2690 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002692 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002693 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002694 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002695 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002696 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2697 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002698 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002699 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002700 break;
2701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 }
2703
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002704 std::unique_ptr<CommandEntry> commandEntry =
2705 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002706 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002708 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002709 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710}
2711
2712void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002713 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002714 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002715 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002716 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002718 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002719 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002720 ATRACE_NAME(message.c_str());
2721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722#if DEBUG_DISPATCH_CYCLE
2723 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002724 "globalScaleFactor=%f, pointerIds=0x%x %s",
2725 connection->getInputChannelName().c_str(), inputTarget.flags,
2726 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2727 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728#endif
2729
2730 // Skip this event if the connection status is not normal.
2731 // We don't want to enqueue additional outbound events if the connection is broken.
2732 if (connection->status != Connection::STATUS_NORMAL) {
2733#if DEBUG_DISPATCH_CYCLE
2734 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736#endif
2737 return;
2738 }
2739
2740 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002741 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2742 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2743 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002744 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002746 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002747 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002748 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002749 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 if (!splitMotionEntry) {
2751 return; // split event was dropped
2752 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002753 if (DEBUG_FOCUS) {
2754 ALOGD("channel '%s' ~ Split motion event.",
2755 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002756 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002757 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002758 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2759 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 return;
2761 }
2762 }
2763
2764 // Not splitting. Enqueue dispatch entries for the event as is.
2765 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2766}
2767
2768void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002770 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002771 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002772 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002774 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002775 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002776 ATRACE_NAME(message.c_str());
2777 }
2778
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002779 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780
2781 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002782 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002784 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002786 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002787 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002788 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002789 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002790 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002792 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002793 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794
2795 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002796 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 startDispatchCycleLocked(currentTime, connection);
2798 }
2799}
2800
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002802 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002803 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002804 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002805 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002806 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2807 connection->getInputChannelName().c_str(),
2808 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002809 ATRACE_NAME(message.c_str());
2810 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002811 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 if (!(inputTargetFlags & dispatchMode)) {
2813 return;
2814 }
2815 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2816
2817 // This is a new event.
2818 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002819 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002820 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002822 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2823 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002824 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002826 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002827 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002828 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002829 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002830 dispatchEntry->resolvedAction = keyEntry.action;
2831 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2834 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2837 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 return; // skip the inconsistent event
2840 }
2841 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002844 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002845 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002846 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2847 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2848 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2849 static_cast<int32_t>(IdGenerator::Source::OTHER);
2850 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2852 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2853 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2854 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2855 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2856 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2857 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2858 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2859 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2860 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2861 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002862 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002863 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002864 }
2865 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002866 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2867 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002869 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2870 "event",
2871 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002873 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002876 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2878 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2879 }
2880 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2881 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2885 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002887 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2888 "event",
2889 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 return; // skip the inconsistent event
2892 }
2893
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002894 dispatchEntry->resolvedEventId =
2895 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2896 ? mIdGenerator.nextId()
2897 : motionEntry.id;
2898 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2899 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2900 ") to MotionEvent(id=0x%" PRIx32 ").",
2901 motionEntry.id, dispatchEntry->resolvedEventId);
2902 ATRACE_NAME(message.c_str());
2903 }
2904
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002905 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002906 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002907
2908 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002910 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002911 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2912 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002913 break;
2914 }
Chris Yef59a2f42020-10-16 12:55:26 -07002915 case EventEntry::Type::SENSOR: {
2916 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2917 break;
2918 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002919 case EventEntry::Type::CONFIGURATION_CHANGED:
2920 case EventEntry::Type::DEVICE_RESET: {
2921 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002922 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002923 break;
2924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 }
2926
2927 // Remember that we are waiting for this dispatch to complete.
2928 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002929 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 }
2931
2932 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002933 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002934 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002935}
2936
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002937/**
2938 * This function is purely for debugging. It helps us understand where the user interaction
2939 * was taking place. For example, if user is touching launcher, we will see a log that user
2940 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2941 * We will see both launcher and wallpaper in that list.
2942 * Once the interaction with a particular set of connections starts, no new logs will be printed
2943 * until the set of interacted connections changes.
2944 *
2945 * The following items are skipped, to reduce the logspam:
2946 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2947 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2948 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2949 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2950 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002951 */
2952void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2953 const std::vector<InputTarget>& targets) {
2954 // Skip ACTION_UP events, and all events other than keys and motions
2955 if (entry.type == EventEntry::Type::KEY) {
2956 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2957 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2958 return;
2959 }
2960 } else if (entry.type == EventEntry::Type::MOTION) {
2961 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2962 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2963 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2964 return;
2965 }
2966 } else {
2967 return; // Not a key or a motion
2968 }
2969
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07002970 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002971 std::vector<sp<Connection>> newConnections;
2972 for (const InputTarget& target : targets) {
2973 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2974 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2975 continue; // Skip windows that receive ACTION_OUTSIDE
2976 }
2977
2978 sp<IBinder> token = target.inputChannel->getConnectionToken();
2979 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002980 if (connection == nullptr) {
2981 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002982 }
2983 newConnectionTokens.insert(std::move(token));
2984 newConnections.emplace_back(connection);
2985 }
2986 if (newConnectionTokens == mInteractionConnectionTokens) {
2987 return; // no change
2988 }
2989 mInteractionConnectionTokens = newConnectionTokens;
2990
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002991 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002992 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002993 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002994 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002995 std::string message = "Interaction with: " + targetList;
2996 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002997 message += "<none>";
2998 }
2999 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3000}
3001
chaviwfd6d3512019-03-25 13:23:49 -07003002void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003003 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003004 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003005 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3006 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003007 return;
3008 }
3009
Vishnu Nairc519ff72021-01-21 08:23:08 -08003010 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003011 if (focusedToken == token) {
3012 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003013 return;
3014 }
3015
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003016 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3017 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003018 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003019 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020}
3021
3022void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003023 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003024 if (ATRACE_ENABLED()) {
3025 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003027 ATRACE_NAME(message.c_str());
3028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031#endif
3032
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003033 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3034 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003036 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003037 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003038 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039
3040 // Publish the event.
3041 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003042 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3043 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003044 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003045 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3046 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003049 status = connection->inputPublisher
3050 .publishKeyEvent(dispatchEntry->seq,
3051 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3052 keyEntry.source, keyEntry.displayId,
3053 std::move(hmac), dispatchEntry->resolvedAction,
3054 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3055 keyEntry.scanCode, keyEntry.metaState,
3056 keyEntry.repeatCount, keyEntry.downTime,
3057 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 }
3060
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003061 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003062 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003065 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003066
chaviw82357092020-01-28 13:13:06 -08003067 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003068 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3070 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003071 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003072 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3073 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003074 // Don't apply window scale here since we don't want scale to affect raw
3075 // coordinates. The scale will be sent back to the client and applied
3076 // later when requesting relative coordinates.
3077 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3078 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 }
3080 usingCoords = scaledCoords;
3081 }
3082 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 // We don't want the dispatch target to know.
3084 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003085 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 scaledCoords[i].clear();
3087 }
3088 usingCoords = scaledCoords;
3089 }
3090 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003091
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003092 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093
3094 // Publish the motion event.
3095 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003096 .publishMotionEvent(dispatchEntry->seq,
3097 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003098 motionEntry.deviceId, motionEntry.source,
3099 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003100 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003101 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003103 motionEntry.edgeFlags, motionEntry.metaState,
3104 motionEntry.buttonState,
3105 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003106 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003107 motionEntry.xPrecision, motionEntry.yPrecision,
3108 motionEntry.xCursorPosition,
3109 motionEntry.yCursorPosition,
3110 motionEntry.downTime, motionEntry.eventTime,
3111 motionEntry.pointerCount,
3112 motionEntry.pointerProperties, usingCoords);
3113 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 break;
3115 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003116
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003117 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003118 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003119 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003120 focusEntry.id,
3121 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003122 mInTouchMode);
3123 break;
3124 }
3125
Prabir Pradhan99987712020-11-10 18:43:05 -08003126 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3127 const auto& captureEntry =
3128 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3129 status = connection->inputPublisher
3130 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3131 captureEntry.pointerCaptureEnabled);
3132 break;
3133 }
3134
arthurhungb89ccb02020-12-30 16:19:01 +08003135 case EventEntry::Type::DRAG: {
3136 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3137 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3138 dragEntry.id, dragEntry.x,
3139 dragEntry.y,
3140 dragEntry.isExiting);
3141 break;
3142 }
3143
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003144 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003145 case EventEntry::Type::DEVICE_RESET:
3146 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003147 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003148 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
3152
3153 // Check the result.
3154 if (status) {
3155 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003156 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 "This is unexpected because the wait queue is empty, so the pipe "
3159 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003160 "event to it, status=%s(%d)",
3161 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3162 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3164 } else {
3165 // Pipe is full and we are waiting for the app to finish process some events
3166 // before sending more events to it.
3167#if DEBUG_DISPATCH_CYCLE
3168 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 "waiting for the application to catch up",
3170 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 }
3173 } else {
3174 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003175 "status=%s(%d)",
3176 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3177 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3179 }
3180 return;
3181 }
3182
3183 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003184 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3185 connection->outboundQueue.end(),
3186 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003187 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003188 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003189 if (connection->responsive) {
3190 mAnrTracker.insert(dispatchEntry->timeoutTime,
3191 connection->inputChannel->getConnectionToken());
3192 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003193 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 }
3195}
3196
chaviw09c8d2d2020-08-24 15:48:26 -07003197std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3198 size_t size;
3199 switch (event.type) {
3200 case VerifiedInputEvent::Type::KEY: {
3201 size = sizeof(VerifiedKeyEvent);
3202 break;
3203 }
3204 case VerifiedInputEvent::Type::MOTION: {
3205 size = sizeof(VerifiedMotionEvent);
3206 break;
3207 }
3208 }
3209 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3210 return mHmacKeyManager.sign(start, size);
3211}
3212
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003213const std::array<uint8_t, 32> InputDispatcher::getSignature(
3214 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3215 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3216 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3217 // Only sign events up and down events as the purely move events
3218 // are tied to their up/down counterparts so signing would be redundant.
3219 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3220 verifiedEvent.actionMasked = actionMasked;
3221 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003222 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003223 }
3224 return INVALID_HMAC;
3225}
3226
3227const std::array<uint8_t, 32> InputDispatcher::getSignature(
3228 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3229 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3230 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3231 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003232 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003233}
3234
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003237 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238#if DEBUG_DISPATCH_CYCLE
3239 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241#endif
3242
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 if (connection->status == Connection::STATUS_BROKEN ||
3244 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 return;
3246 }
3247
3248 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003249 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250}
3251
3252void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 const sp<Connection>& connection,
3254 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255#if DEBUG_DISPATCH_CYCLE
3256 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258#endif
3259
3260 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003261 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003262 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003263 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003264 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265
3266 // The connection appears to be unrecoverably broken.
3267 // Ignore already broken or zombie connections.
3268 if (connection->status == Connection::STATUS_NORMAL) {
3269 connection->status = Connection::STATUS_BROKEN;
3270
3271 if (notify) {
3272 // Notify other system components.
3273 onDispatchCycleBrokenLocked(currentTime, connection);
3274 }
3275 }
3276}
3277
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003278void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3279 while (!queue.empty()) {
3280 DispatchEntry* dispatchEntry = queue.front();
3281 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003282 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 }
3284}
3285
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003286void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003288 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 }
3290 delete dispatchEntry;
3291}
3292
3293int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3294 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3295
3296 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003297 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003299 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 "fd=%d, events=0x%x",
3302 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 return 0; // remove the callback
3304 }
3305
3306 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003307 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3309 if (!(events & ALOOPER_EVENT_INPUT)) {
3310 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311 "events=0x%x",
3312 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313 return 1;
3314 }
3315
3316 nsecs_t currentTime = now();
3317 bool gotOne = false;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00003318 status_t status = OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 for (;;) {
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003320 Result<InputPublisher::ConsumerResponse> result =
3321 connection->inputPublisher.receiveConsumerResponse();
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00003322 if (!result.ok()) {
3323 status = result.error().code();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 break;
3325 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003326
3327 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3328 const InputPublisher::Finished& finish =
3329 std::get<InputPublisher::Finished>(*result);
3330 d->finishDispatchCycleLocked(currentTime, connection, finish.seq,
3331 finish.handled, finish.consumeTime);
3332 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
3333 // TODO(b/167947340): Report this data to LatencyTracker
3334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 gotOne = true;
3336 }
3337 if (gotOne) {
3338 d->runCommandsLockedInterruptible();
3339 if (status == WOULD_BLOCK) {
3340 return 1;
3341 }
3342 }
3343
3344 notify = status != DEAD_OBJECT || !connection->monitor;
3345 if (notify) {
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003346 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3347 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3348 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 }
3350 } else {
3351 // Monitor channels are never explicitly unregistered.
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003352 // We do it automatically when the remote endpoint is closed so don't warn about them.
arthurhungd352cb32020-04-28 17:09:28 +08003353 const bool stillHaveWindowHandle =
3354 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3355 nullptr;
3356 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 if (notify) {
3358 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 "events=0x%x",
3360 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 }
3362 }
3363
Garfield Tan15601662020-09-22 15:32:38 -07003364 // Remove the channel.
3365 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368}
3369
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003372 for (const auto& [fd, connection] : mConnectionsByFd) {
3373 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
3375}
3376
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003378 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003379 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3380 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3381}
3382
3383void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3384 const CancelationOptions& options,
3385 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3386 for (const auto& it : monitorsByDisplay) {
3387 const std::vector<Monitor>& monitors = it.second;
3388 for (const Monitor& monitor : monitors) {
3389 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003390 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003391 }
3392}
3393
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003395 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003396 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003397 if (connection == nullptr) {
3398 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003400
3401 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402}
3403
3404void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3405 const sp<Connection>& connection, const CancelationOptions& options) {
3406 if (connection->status == Connection::STATUS_BROKEN) {
3407 return;
3408 }
3409
3410 nsecs_t currentTime = now();
3411
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003412 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003413 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003415 if (cancelationEvents.empty()) {
3416 return;
3417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003419 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3420 "with reality: %s, mode=%d.",
3421 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3422 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003424
3425 InputTarget target;
3426 sp<InputWindowHandle> windowHandle =
3427 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3428 if (windowHandle != nullptr) {
3429 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003430 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003431 target.globalScaleFactor = windowInfo->globalScaleFactor;
3432 }
3433 target.inputChannel = connection->inputChannel;
3434 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3435
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003436 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003437 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003438 switch (cancelationEventEntry->type) {
3439 case EventEntry::Type::KEY: {
3440 logOutboundKeyDetails("cancel - ",
3441 static_cast<const KeyEntry&>(*cancelationEventEntry));
3442 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003444 case EventEntry::Type::MOTION: {
3445 logOutboundMotionDetails("cancel - ",
3446 static_cast<const MotionEntry&>(*cancelationEventEntry));
3447 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003449 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003450 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3451 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003452 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003453 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003454 break;
3455 }
3456 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003457 case EventEntry::Type::DEVICE_RESET:
3458 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003459 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003460 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003461 break;
3462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
3464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003465 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3466 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003468
3469 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470}
3471
Svet Ganov5d3bc372020-01-26 23:11:07 -08003472void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3473 const sp<Connection>& connection) {
3474 if (connection->status == Connection::STATUS_BROKEN) {
3475 return;
3476 }
3477
3478 nsecs_t currentTime = now();
3479
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003480 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003481 connection->inputState.synthesizePointerDownEvents(currentTime);
3482
3483 if (downEvents.empty()) {
3484 return;
3485 }
3486
3487#if DEBUG_OUTBOUND_EVENT_DETAILS
3488 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3489 connection->getInputChannelName().c_str(), downEvents.size());
3490#endif
3491
3492 InputTarget target;
3493 sp<InputWindowHandle> windowHandle =
3494 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3495 if (windowHandle != nullptr) {
3496 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003497 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003498 target.globalScaleFactor = windowInfo->globalScaleFactor;
3499 }
3500 target.inputChannel = connection->inputChannel;
3501 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3502
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003503 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003504 switch (downEventEntry->type) {
3505 case EventEntry::Type::MOTION: {
3506 logOutboundMotionDetails("down - ",
3507 static_cast<const MotionEntry&>(*downEventEntry));
3508 break;
3509 }
3510
3511 case EventEntry::Type::KEY:
3512 case EventEntry::Type::FOCUS:
3513 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003514 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003515 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003516 case EventEntry::Type::SENSOR:
3517 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003518 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003519 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003520 break;
3521 }
3522 }
3523
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003524 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3525 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003526 }
3527
3528 startDispatchCycleLocked(currentTime, connection);
3529}
3530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003531std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3532 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 ALOG_ASSERT(pointerIds.value != 0);
3534
3535 uint32_t splitPointerIndexMap[MAX_POINTERS];
3536 PointerProperties splitPointerProperties[MAX_POINTERS];
3537 PointerCoords splitPointerCoords[MAX_POINTERS];
3538
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003539 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 uint32_t splitPointerCount = 0;
3541
3542 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003543 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003545 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 uint32_t pointerId = uint32_t(pointerProperties.id);
3547 if (pointerIds.hasBit(pointerId)) {
3548 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3549 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3550 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003551 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 splitPointerCount += 1;
3553 }
3554 }
3555
3556 if (splitPointerCount != pointerIds.count()) {
3557 // This is bad. We are missing some of the pointers that we expected to deliver.
3558 // Most likely this indicates that we received an ACTION_MOVE events that has
3559 // different pointer ids than we expected based on the previous ACTION_DOWN
3560 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3561 // in this way.
3562 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 "we expected there to be %d pointers. This probably means we received "
3564 "a broken sequence of pointer ids from the input device.",
3565 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003566 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 }
3568
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003569 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003571 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3572 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3574 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003575 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 uint32_t pointerId = uint32_t(pointerProperties.id);
3577 if (pointerIds.hasBit(pointerId)) {
3578 if (pointerIds.count() == 1) {
3579 // The first/last pointer went down/up.
3580 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003581 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003582 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3583 ? AMOTION_EVENT_ACTION_CANCEL
3584 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 } else {
3586 // A secondary pointer went down/up.
3587 uint32_t splitPointerIndex = 0;
3588 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3589 splitPointerIndex += 1;
3590 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591 action = maskedAction |
3592 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 }
3594 } else {
3595 // An unrelated pointer changed.
3596 action = AMOTION_EVENT_ACTION_MOVE;
3597 }
3598 }
3599
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003600 int32_t newId = mIdGenerator.nextId();
3601 if (ATRACE_ENABLED()) {
3602 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3603 ") to MotionEvent(id=0x%" PRIx32 ").",
3604 originalMotionEntry.id, newId);
3605 ATRACE_NAME(message.c_str());
3606 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003607 std::unique_ptr<MotionEntry> splitMotionEntry =
3608 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3609 originalMotionEntry.deviceId, originalMotionEntry.source,
3610 originalMotionEntry.displayId,
3611 originalMotionEntry.policyFlags, action,
3612 originalMotionEntry.actionButton,
3613 originalMotionEntry.flags, originalMotionEntry.metaState,
3614 originalMotionEntry.buttonState,
3615 originalMotionEntry.classification,
3616 originalMotionEntry.edgeFlags,
3617 originalMotionEntry.xPrecision,
3618 originalMotionEntry.yPrecision,
3619 originalMotionEntry.xCursorPosition,
3620 originalMotionEntry.yCursorPosition,
3621 originalMotionEntry.downTime, splitPointerCount,
3622 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003624 if (originalMotionEntry.injectionState) {
3625 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 splitMotionEntry->injectionState->refCount += 1;
3627 }
3628
3629 return splitMotionEntry;
3630}
3631
3632void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3633#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003634 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635#endif
3636
3637 bool needWake;
3638 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003639 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003641 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3642 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3643 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 } // release lock
3645
3646 if (needWake) {
3647 mLooper->wake();
3648 }
3649}
3650
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003651/**
3652 * If one of the meta shortcuts is detected, process them here:
3653 * Meta + Backspace -> generate BACK
3654 * Meta + Enter -> generate HOME
3655 * This will potentially overwrite keyCode and metaState.
3656 */
3657void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003658 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003659 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3660 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3661 if (keyCode == AKEYCODE_DEL) {
3662 newKeyCode = AKEYCODE_BACK;
3663 } else if (keyCode == AKEYCODE_ENTER) {
3664 newKeyCode = AKEYCODE_HOME;
3665 }
3666 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003667 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003668 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003669 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003670 keyCode = newKeyCode;
3671 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3672 }
3673 } else if (action == AKEY_EVENT_ACTION_UP) {
3674 // In order to maintain a consistent stream of up and down events, check to see if the key
3675 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3676 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003677 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003678 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003679 auto replacementIt = mReplacedKeys.find(replacement);
3680 if (replacementIt != mReplacedKeys.end()) {
3681 keyCode = replacementIt->second;
3682 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003683 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3684 }
3685 }
3686}
3687
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3689#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003690 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3691 "policyFlags=0x%x, action=0x%x, "
3692 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3693 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3694 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3695 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696#endif
3697 if (!validateKeyEvent(args->action)) {
3698 return;
3699 }
3700
3701 uint32_t policyFlags = args->policyFlags;
3702 int32_t flags = args->flags;
3703 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003704 // InputDispatcher tracks and generates key repeats on behalf of
3705 // whatever notifies it, so repeatCount should always be set to 0
3706 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3708 policyFlags |= POLICY_FLAG_VIRTUAL;
3709 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 if (policyFlags & POLICY_FLAG_FUNCTION) {
3712 metaState |= AMETA_FUNCTION_ON;
3713 }
3714
3715 policyFlags |= POLICY_FLAG_TRUSTED;
3716
Michael Wright78f24442014-08-06 15:55:28 -07003717 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003718 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003719
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003721 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003722 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3723 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724
Michael Wright2b3c3302018-03-02 17:19:13 +00003725 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003727 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3728 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003729 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 bool needWake;
3733 { // acquire lock
3734 mLock.lock();
3735
3736 if (shouldSendKeyToInputFilterLocked(args)) {
3737 mLock.unlock();
3738
3739 policyFlags |= POLICY_FLAG_FILTERED;
3740 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3741 return; // event was consumed by the filter
3742 }
3743
3744 mLock.lock();
3745 }
3746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003747 std::unique_ptr<KeyEntry> newEntry =
3748 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3749 args->displayId, policyFlags, args->action, flags,
3750 keyCode, args->scanCode, metaState, repeatCount,
3751 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003753 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 mLock.unlock();
3755 } // release lock
3756
3757 if (needWake) {
3758 mLooper->wake();
3759 }
3760}
3761
3762bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3763 return mInputFilterEnabled;
3764}
3765
3766void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3767#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003768 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3769 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003770 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3771 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003772 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003773 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3774 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3775 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3776 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 for (uint32_t i = 0; i < args->pointerCount; i++) {
3778 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 "x=%f, y=%f, pressure=%f, size=%f, "
3780 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3781 "orientation=%f",
3782 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3783 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3784 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3785 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3786 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3787 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3788 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3789 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3790 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3791 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 }
3793#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003794 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3795 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 return;
3797 }
3798
3799 uint32_t policyFlags = args->policyFlags;
3800 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003801
3802 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003803 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003804 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3805 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003806 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808
3809 bool needWake;
3810 { // acquire lock
3811 mLock.lock();
3812
3813 if (shouldSendMotionToInputFilterLocked(args)) {
3814 mLock.unlock();
3815
3816 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003817 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003818 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3819 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003820 args->metaState, args->buttonState, args->classification, transform,
3821 args->xPrecision, args->yPrecision, args->xCursorPosition,
3822 args->yCursorPosition, args->downTime, args->eventTime,
3823 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824
3825 policyFlags |= POLICY_FLAG_FILTERED;
3826 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3827 return; // event was consumed by the filter
3828 }
3829
3830 mLock.lock();
3831 }
3832
3833 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003834 std::unique_ptr<MotionEntry> newEntry =
3835 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3836 args->source, args->displayId, policyFlags,
3837 args->action, args->actionButton, args->flags,
3838 args->metaState, args->buttonState,
3839 args->classification, args->edgeFlags,
3840 args->xPrecision, args->yPrecision,
3841 args->xCursorPosition, args->yCursorPosition,
3842 args->downTime, args->pointerCount,
3843 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003845 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 mLock.unlock();
3847 } // release lock
3848
3849 if (needWake) {
3850 mLooper->wake();
3851 }
3852}
3853
Chris Yef59a2f42020-10-16 12:55:26 -07003854void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3855#if DEBUG_INBOUND_EVENT_DETAILS
3856 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3857 " sensorType=%s",
3858 args->id, args->eventTime, args->deviceId, args->source,
3859 NamedEnum::string(args->sensorType).c_str());
3860#endif
3861
3862 bool needWake;
3863 { // acquire lock
3864 mLock.lock();
3865
3866 // Just enqueue a new sensor event.
3867 std::unique_ptr<SensorEntry> newEntry =
3868 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3869 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3870 args->sensorType, args->accuracy,
3871 args->accuracyChanged, args->values);
3872
3873 needWake = enqueueInboundEventLocked(std::move(newEntry));
3874 mLock.unlock();
3875 } // release lock
3876
3877 if (needWake) {
3878 mLooper->wake();
3879 }
3880}
3881
Chris Yefb552902021-02-03 17:18:37 -08003882void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3883#if DEBUG_INBOUND_EVENT_DETAILS
3884 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3885 args->deviceId, args->isOn);
3886#endif
3887 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3888}
3889
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003891 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892}
3893
3894void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3895#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003896 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003897 "switchMask=0x%08x",
3898 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899#endif
3900
3901 uint32_t policyFlags = args->policyFlags;
3902 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904}
3905
3906void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3907#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003908 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3909 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910#endif
3911
3912 bool needWake;
3913 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003914 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003916 std::unique_ptr<DeviceResetEntry> newEntry =
3917 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3918 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 } // release lock
3920
3921 if (needWake) {
3922 mLooper->wake();
3923 }
3924}
3925
Prabir Pradhan7e186182020-11-10 13:56:45 -08003926void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3927#if DEBUG_INBOUND_EVENT_DETAILS
3928 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3929 args->enabled ? "true" : "false");
3930#endif
3931
Prabir Pradhan99987712020-11-10 18:43:05 -08003932 bool needWake;
3933 { // acquire lock
3934 std::scoped_lock _l(mLock);
3935 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3936 args->enabled);
3937 needWake = enqueueInboundEventLocked(std::move(entry));
3938 } // release lock
3939
3940 if (needWake) {
3941 mLooper->wake();
3942 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003943}
3944
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003945InputEventInjectionResult InputDispatcher::injectInputEvent(
3946 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3947 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948#if DEBUG_INBOUND_EVENT_DETAILS
3949 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003950 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3951 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003953 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954
3955 policyFlags |= POLICY_FLAG_INJECTED;
3956 if (hasInjectionPermission(injectorPid, injectorUid)) {
3957 policyFlags |= POLICY_FLAG_TRUSTED;
3958 }
3959
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003960 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003963 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3964 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003965 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003966 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003969 int32_t flags = incomingKey.getFlags();
3970 int32_t keyCode = incomingKey.getKeyCode();
3971 int32_t metaState = incomingKey.getMetaState();
3972 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003974 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003975 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003976 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3977 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3978 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3981 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003982 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003983
3984 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3985 android::base::Timer t;
3986 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3987 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3988 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3989 std::to_string(t.duration().count()).c_str());
3990 }
3991 }
3992
3993 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003994 std::unique_ptr<KeyEntry> injectedEntry =
3995 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3996 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3997 incomingKey.getDisplayId(), policyFlags, action,
3998 flags, keyCode, incomingKey.getScanCode(), metaState,
3999 incomingKey.getRepeatCount(),
4000 incomingKey.getDownTime());
4001 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004002 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 }
4004
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004005 case AINPUT_EVENT_TYPE_MOTION: {
4006 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
4007 int32_t action = motionEvent->getAction();
4008 size_t pointerCount = motionEvent->getPointerCount();
4009 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
4010 int32_t actionButton = motionEvent->getActionButton();
4011 int32_t displayId = motionEvent->getDisplayId();
4012 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004013 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004014 }
4015
4016 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4017 nsecs_t eventTime = motionEvent->getEventTime();
4018 android::base::Timer t;
4019 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4020 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4021 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4022 std::to_string(t.duration().count()).c_str());
4023 }
4024 }
4025
4026 mLock.lock();
4027 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
4028 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004029 std::unique_ptr<MotionEntry> injectedEntry =
4030 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4031 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4032 motionEvent->getDisplayId(), policyFlags, action,
4033 actionButton, motionEvent->getFlags(),
4034 motionEvent->getMetaState(),
4035 motionEvent->getButtonState(),
4036 motionEvent->getClassification(),
4037 motionEvent->getEdgeFlags(),
4038 motionEvent->getXPrecision(),
4039 motionEvent->getYPrecision(),
4040 motionEvent->getRawXCursorPosition(),
4041 motionEvent->getRawYCursorPosition(),
4042 motionEvent->getDownTime(),
4043 uint32_t(pointerCount), pointerProperties,
4044 samplePointerCoords, motionEvent->getXOffset(),
4045 motionEvent->getYOffset());
4046 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
4048 sampleEventTimes += 1;
4049 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004050 std::unique_ptr<MotionEntry> nextInjectedEntry =
4051 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4052 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4053 motionEvent->getDisplayId(), policyFlags,
4054 action, actionButton, motionEvent->getFlags(),
4055 motionEvent->getMetaState(),
4056 motionEvent->getButtonState(),
4057 motionEvent->getClassification(),
4058 motionEvent->getEdgeFlags(),
4059 motionEvent->getXPrecision(),
4060 motionEvent->getYPrecision(),
4061 motionEvent->getRawXCursorPosition(),
4062 motionEvent->getRawYCursorPosition(),
4063 motionEvent->getDownTime(),
4064 uint32_t(pointerCount), pointerProperties,
4065 samplePointerCoords,
4066 motionEvent->getXOffset(),
4067 motionEvent->getYOffset());
4068 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004069 }
4070 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004074 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004075 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 }
4077
4078 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004079 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 injectionState->injectionIsAsync = true;
4081 }
4082
4083 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004084 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
4086 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004087 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004088 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004089 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 }
4091
4092 mLock.unlock();
4093
4094 if (needWake) {
4095 mLooper->wake();
4096 }
4097
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004098 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004100 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004102 if (syncMode == InputEventInjectionSync::NONE) {
4103 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 } else {
4105 for (;;) {
4106 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004107 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 break;
4109 }
4110
4111 nsecs_t remainingTimeout = endTime - now();
4112 if (remainingTimeout <= 0) {
4113#if DEBUG_INJECTION
4114 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004117 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 break;
4119 }
4120
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004121 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 }
4123
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004124 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4125 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 while (injectionState->pendingForegroundDispatches != 0) {
4127#if DEBUG_INJECTION
4128 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130#endif
4131 nsecs_t remainingTimeout = endTime - now();
4132 if (remainingTimeout <= 0) {
4133#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004134 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4135 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004137 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 break;
4139 }
4140
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004141 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143 }
4144 }
4145
4146 injectionState->release();
4147 } // release lock
4148
4149#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004150 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152#endif
4153
4154 return injectionResult;
4155}
4156
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004157std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004158 std::array<uint8_t, 32> calculatedHmac;
4159 std::unique_ptr<VerifiedInputEvent> result;
4160 switch (event.getType()) {
4161 case AINPUT_EVENT_TYPE_KEY: {
4162 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4163 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4164 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004165 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004166 break;
4167 }
4168 case AINPUT_EVENT_TYPE_MOTION: {
4169 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4170 VerifiedMotionEvent verifiedMotionEvent =
4171 verifiedMotionEventFromMotionEvent(motionEvent);
4172 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004173 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004174 break;
4175 }
4176 default: {
4177 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4178 return nullptr;
4179 }
4180 }
4181 if (calculatedHmac == INVALID_HMAC) {
4182 return nullptr;
4183 }
4184 if (calculatedHmac != event.getHmac()) {
4185 return nullptr;
4186 }
4187 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004188}
4189
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004191 return injectorUid == 0 ||
4192 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193}
4194
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004195void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004196 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004197 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 if (injectionState) {
4199#if DEBUG_INJECTION
4200 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 "injectorPid=%d, injectorUid=%d",
4202 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203#endif
4204
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004205 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 // Log the outcome since the injector did not wait for the injection result.
4207 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004208 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 ALOGV("Asynchronous input event injection succeeded.");
4210 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004211 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 ALOGW("Asynchronous input event injection failed.");
4213 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004214 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004215 ALOGW("Asynchronous input event injection permission denied.");
4216 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004217 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004218 ALOGW("Asynchronous input event injection timed out.");
4219 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004220 case InputEventInjectionResult::PENDING:
4221 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4222 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224 }
4225
4226 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004227 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 }
4229}
4230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004231void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4232 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 if (injectionState) {
4234 injectionState->pendingForegroundDispatches += 1;
4235 }
4236}
4237
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4239 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 if (injectionState) {
4241 injectionState->pendingForegroundDispatches -= 1;
4242
4243 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004244 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 }
4246 }
4247}
4248
Vishnu Nairad321cd2020-08-20 16:40:21 -07004249const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004250 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004251 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4252 auto it = mWindowHandlesByDisplay.find(displayId);
4253 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004254}
4255
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004257 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004258 if (windowHandleToken == nullptr) {
4259 return nullptr;
4260 }
4261
Arthur Hungb92218b2018-08-14 12:00:21 +08004262 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004263 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004264 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004265 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004266 return windowHandle;
4267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004270 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271}
4272
Vishnu Nairad321cd2020-08-20 16:40:21 -07004273sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4274 int displayId) const {
4275 if (windowHandleToken == nullptr) {
4276 return nullptr;
4277 }
4278
4279 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4280 if (windowHandle->getToken() == windowHandleToken) {
4281 return windowHandle;
4282 }
4283 }
4284 return nullptr;
4285}
4286
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004287sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4288 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004289 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004290 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004291 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004292 if (handle->getId() == windowHandle->getId() &&
4293 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004294 if (windowHandle->getInfo()->displayId != it.first) {
4295 ALOGE("Found window %s in display %" PRId32
4296 ", but it should belong to display %" PRId32,
4297 windowHandle->getName().c_str(), it.first,
4298 windowHandle->getInfo()->displayId);
4299 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004300 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 }
4303 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004304 return nullptr;
4305}
4306
4307sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4308 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4309 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310}
4311
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004312bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4313 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4314 const bool noInputChannel =
4315 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4316 if (connection != nullptr && noInputChannel) {
4317 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4318 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4319 return false;
4320 }
4321
4322 if (connection == nullptr) {
4323 if (!noInputChannel) {
4324 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4325 }
4326 return false;
4327 }
4328 if (!connection->responsive) {
4329 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4330 return false;
4331 }
4332 return true;
4333}
4334
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004335std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4336 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004337 size_t count = mInputChannelsByToken.count(token);
4338 if (count == 0) {
4339 return nullptr;
4340 }
4341 return mInputChannelsByToken.at(token);
4342}
4343
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004344void InputDispatcher::updateWindowHandlesForDisplayLocked(
4345 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4346 if (inputWindowHandles.empty()) {
4347 // Remove all handles on a display if there are no windows left.
4348 mWindowHandlesByDisplay.erase(displayId);
4349 return;
4350 }
4351
4352 // Since we compare the pointer of input window handles across window updates, we need
4353 // to make sure the handle object for the same window stays unchanged across updates.
4354 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004355 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004356 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004357 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004358 }
4359
4360 std::vector<sp<InputWindowHandle>> newHandles;
4361 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4362 if (!handle->updateInfo()) {
4363 // handle no longer valid
4364 continue;
4365 }
4366
4367 const InputWindowInfo* info = handle->getInfo();
4368 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4369 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4370 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004371 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4372 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4373 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004374 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004375 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004376 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004377 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004378 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004379 }
4380
4381 if (info->displayId != displayId) {
4382 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4383 handle->getName().c_str(), displayId, info->displayId);
4384 continue;
4385 }
4386
Robert Carredd13602020-04-13 17:24:34 -07004387 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4388 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004389 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004390 oldHandle->updateFrom(handle);
4391 newHandles.push_back(oldHandle);
4392 } else {
4393 newHandles.push_back(handle);
4394 }
4395 }
4396
4397 // Insert or replace
4398 mWindowHandlesByDisplay[displayId] = newHandles;
4399}
4400
Arthur Hung72d8dc32020-03-28 00:48:39 +00004401void InputDispatcher::setInputWindows(
4402 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4403 { // acquire lock
4404 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004405 for (const auto& [displayId, handles] : handlesPerDisplay) {
4406 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004407 }
4408 }
4409 // Wake up poll loop since it may need to make new input dispatching choices.
4410 mLooper->wake();
4411}
4412
Arthur Hungb92218b2018-08-14 12:00:21 +08004413/**
4414 * Called from InputManagerService, update window handle list by displayId that can receive input.
4415 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4416 * If set an empty list, remove all handles from the specific display.
4417 * For focused handle, check if need to change and send a cancel event to previous one.
4418 * For removed handle, check if need to send a cancel event if already in touch.
4419 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004420void InputDispatcher::setInputWindowsLocked(
4421 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004422 if (DEBUG_FOCUS) {
4423 std::string windowList;
4424 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4425 windowList += iwh->getName() + " ";
4426 }
4427 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004430 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4431 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4432 const bool noInputWindow =
4433 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4434 if (noInputWindow && window->getToken() != nullptr) {
4435 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4436 window->getName().c_str());
4437 window->releaseChannel();
4438 }
4439 }
4440
Arthur Hung72d8dc32020-03-28 00:48:39 +00004441 // Copy old handles for release if they are no longer present.
4442 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443
Arthur Hung72d8dc32020-03-28 00:48:39 +00004444 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004445
Vishnu Nair958da932020-08-21 17:12:37 -07004446 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4447 if (mLastHoverWindowHandle &&
4448 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4449 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004450 mLastHoverWindowHandle = nullptr;
4451 }
4452
Vishnu Nairc519ff72021-01-21 08:23:08 -08004453 std::optional<FocusResolver::FocusChanges> changes =
4454 mFocusResolver.setInputWindows(displayId, windowHandles);
4455 if (changes) {
4456 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004459 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4460 mTouchStatesByDisplay.find(displayId);
4461 if (stateIt != mTouchStatesByDisplay.end()) {
4462 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004463 for (size_t i = 0; i < state.windows.size();) {
4464 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004465 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004466 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004467 ALOGD("Touched window was removed: %s in display %" PRId32,
4468 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004469 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004470 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004471 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4472 if (touchedInputChannel != nullptr) {
4473 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4474 "touched window was removed");
4475 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004477 state.windows.erase(state.windows.begin() + i);
4478 } else {
4479 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 }
4481 }
arthurhungb89ccb02020-12-30 16:19:01 +08004482
arthurhung6d4bed92021-03-17 11:59:33 +08004483 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004484 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004485 if (mDragState &&
4486 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004487 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004488 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004489 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004490 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004491
Arthur Hung72d8dc32020-03-28 00:48:39 +00004492 // Release information for windows that are no longer present.
4493 // This ensures that unused input channels are released promptly.
4494 // Otherwise, they might stick around until the window handle is destroyed
4495 // which might not happen until the next GC.
4496 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004497 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004498 if (DEBUG_FOCUS) {
4499 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004500 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004501 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004502 // To avoid making too many calls into the compat framework, only
4503 // check for window flags when windows are going away.
4504 // TODO(b/157929241) : delete this. This is only needed temporarily
4505 // in order to gather some data about the flag usage
4506 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4507 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4508 oldWindowHandle->getName().c_str());
4509 if (mCompatService != nullptr) {
4510 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4511 oldWindowHandle->getInfo()->ownerUid);
4512 }
4513 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004514 }
chaviw291d88a2019-02-14 10:33:58 -08004515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516}
4517
4518void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004519 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004520 if (DEBUG_FOCUS) {
4521 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4522 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4523 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004524 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004525 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
Chris Yea209fde2020-07-22 13:54:51 -07004527 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004528 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004529
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004530 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4531 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004532 }
4533
Chris Yea209fde2020-07-22 13:54:51 -07004534 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004535 if (inputApplicationHandle != nullptr) {
4536 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4537 } else {
4538 mFocusedApplicationHandlesByDisplay.erase(displayId);
4539 }
4540
4541 // No matter what the old focused application was, stop waiting on it because it is
4542 // no longer focused.
4543 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 } // release lock
4545
4546 // Wake up poll loop since it may need to make new input dispatching choices.
4547 mLooper->wake();
4548}
4549
Tiger Huang721e26f2018-07-24 22:26:19 +08004550/**
4551 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4552 * the display not specified.
4553 *
4554 * We track any unreleased events for each window. If a window loses the ability to receive the
4555 * released event, we will send a cancel event to it. So when the focused display is changed, we
4556 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4557 * display. The display-specified events won't be affected.
4558 */
4559void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004560 if (DEBUG_FOCUS) {
4561 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4562 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004563 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004564 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004565
4566 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004567 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004568 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004569 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004570 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004571 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004572 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 CancelationOptions
4574 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4575 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004576 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004577 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4578 }
4579 }
4580 mFocusedDisplayId = displayId;
4581
Chris Ye3c2d6f52020-08-09 10:39:48 -07004582 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004583 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004584 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004585
Vishnu Nairad321cd2020-08-20 16:40:21 -07004586 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004587 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004588 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004589 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004590 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004591 }
4592 }
4593 }
4594
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004595 if (DEBUG_FOCUS) {
4596 logDispatchStateLocked();
4597 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004598 } // release lock
4599
4600 // Wake up poll loop since it may need to make new input dispatching choices.
4601 mLooper->wake();
4602}
4603
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004605 if (DEBUG_FOCUS) {
4606 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
4609 bool changed;
4610 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004611 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612
4613 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4614 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004615 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 }
4617
4618 if (mDispatchEnabled && !enabled) {
4619 resetAndDropEverythingLocked("dispatcher is being disabled");
4620 }
4621
4622 mDispatchEnabled = enabled;
4623 mDispatchFrozen = frozen;
4624 changed = true;
4625 } else {
4626 changed = false;
4627 }
4628
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004629 if (DEBUG_FOCUS) {
4630 logDispatchStateLocked();
4631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 } // release lock
4633
4634 if (changed) {
4635 // Wake up poll loop since it may need to make new input dispatching choices.
4636 mLooper->wake();
4637 }
4638}
4639
4640void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004641 if (DEBUG_FOCUS) {
4642 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644
4645 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004646 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647
4648 if (mInputFilterEnabled == enabled) {
4649 return;
4650 }
4651
4652 mInputFilterEnabled = enabled;
4653 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4654 } // release lock
4655
4656 // Wake up poll loop since there might be work to do to drop everything.
4657 mLooper->wake();
4658}
4659
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004660void InputDispatcher::setInTouchMode(bool inTouchMode) {
4661 std::scoped_lock lock(mLock);
4662 mInTouchMode = inTouchMode;
4663}
4664
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004665void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4666 if (opacity < 0 || opacity > 1) {
4667 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4668 return;
4669 }
4670
4671 std::scoped_lock lock(mLock);
4672 mMaximumObscuringOpacityForTouch = opacity;
4673}
4674
4675void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4676 std::scoped_lock lock(mLock);
4677 mBlockUntrustedTouchesMode = mode;
4678}
4679
arthurhungb89ccb02020-12-30 16:19:01 +08004680bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4681 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004682 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004683 if (DEBUG_FOCUS) {
4684 ALOGD("Trivial transfer to same window.");
4685 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004686 return true;
4687 }
4688
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004690 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691
chaviwfbe5d9c2018-12-26 12:23:37 -08004692 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4693 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004694 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004695 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 return false;
4697 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004698 if (DEBUG_FOCUS) {
4699 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4700 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004703 if (DEBUG_FOCUS) {
4704 ALOGD("Cannot transfer focus because windows are on different displays.");
4705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 return false;
4707 }
4708
4709 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004710 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4711 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004712 for (size_t i = 0; i < state.windows.size(); i++) {
4713 const TouchedWindow& touchedWindow = state.windows[i];
4714 if (touchedWindow.windowHandle == fromWindowHandle) {
4715 int32_t oldTargetFlags = touchedWindow.targetFlags;
4716 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004718 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004720 int32_t newTargetFlags = oldTargetFlags &
4721 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4722 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004723 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
arthurhungb89ccb02020-12-30 16:19:01 +08004725 // Store the dragging window.
4726 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004727 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004728 }
4729
Jeff Brownf086ddb2014-02-11 14:28:48 -08004730 found = true;
4731 goto Found;
4732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 }
4734 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004737 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004738 if (DEBUG_FOCUS) {
4739 ALOGD("Focus transfer failed because from window did not have focus.");
4740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 return false;
4742 }
4743
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004744 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4745 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004746 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004747 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 CancelationOptions
4749 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4750 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004752 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 }
4754
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004755 if (DEBUG_FOCUS) {
4756 logDispatchStateLocked();
4757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 } // release lock
4759
4760 // Wake up poll loop since it may need to make new input dispatching choices.
4761 mLooper->wake();
4762 return true;
4763}
4764
4765void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004766 if (DEBUG_FOCUS) {
4767 ALOGD("Resetting and dropping all events (%s).", reason);
4768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769
4770 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4771 synthesizeCancelationEventsForAllConnectionsLocked(options);
4772
4773 resetKeyRepeatLocked();
4774 releasePendingEventLocked();
4775 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004778 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004779 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004781 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782}
4783
4784void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004785 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 dumpDispatchStateLocked(dump);
4787
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004788 std::istringstream stream(dump);
4789 std::string line;
4790
4791 while (std::getline(stream, line, '\n')) {
4792 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 }
4794}
4795
Prabir Pradhan99987712020-11-10 18:43:05 -08004796std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4797 std::string dump;
4798
4799 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4800 toString(mFocusedWindowRequestedPointerCapture));
4801
4802 std::string windowName = "None";
4803 if (mWindowTokenWithPointerCapture) {
4804 const sp<InputWindowHandle> captureWindowHandle =
4805 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4806 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4807 : "token has capture without window";
4808 }
4809 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4810
4811 return dump;
4812}
4813
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004814void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004815 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4816 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4817 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004818 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
Tiger Huang721e26f2018-07-24 22:26:19 +08004820 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4821 dump += StringPrintf(INDENT "FocusedApplications:\n");
4822 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4823 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004824 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004825 const std::chrono::duration timeout =
4826 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004828 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004829 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004832 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004834
Vishnu Nairc519ff72021-01-21 08:23:08 -08004835 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004836 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004838 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004839 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004840 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4841 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004842 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004843 state.displayId, toString(state.down), toString(state.split),
4844 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004845 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004846 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004847 for (size_t i = 0; i < state.windows.size(); i++) {
4848 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 dump += StringPrintf(INDENT4
4850 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4851 i, touchedWindow.windowHandle->getName().c_str(),
4852 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004853 }
4854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004855 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004856 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004857 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004858 dump += INDENT3 "Portal windows:\n";
4859 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004860 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004861 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4862 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004863 }
4864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004867 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 }
4869
arthurhung6d4bed92021-03-17 11:59:33 +08004870 if (mDragState) {
4871 dump += StringPrintf(INDENT "DragState:\n");
4872 mDragState->dump(dump, INDENT2);
4873 }
4874
Arthur Hungb92218b2018-08-14 12:00:21 +08004875 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004876 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004877 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004878 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004879 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004880 dump += INDENT2 "Windows:\n";
4881 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004882 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004883 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004885 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004886 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004887 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004888 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004889 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004890 "applicationInfo.name=%s, "
4891 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004892 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004893 i, windowInfo->name.c_str(), windowInfo->id,
4894 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004895 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004896 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004897 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004898 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004899 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004900 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004901 windowInfo->frameLeft, windowInfo->frameTop,
4902 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004903 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004904 windowInfo->applicationInfo.name.c_str(),
4905 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004906 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004907 dump += StringPrintf(", inputFeatures=%s",
4908 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004909 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004910 "ms, trustedOverlay=%s, hasToken=%s, "
4911 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004912 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004913 millis(windowInfo->dispatchingTimeout),
4914 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004915 toString(windowInfo->token != nullptr),
4916 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004917 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004918 }
4919 } else {
4920 dump += INDENT2 "Windows: <none>\n";
4921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 }
4923 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004924 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 }
4926
Michael Wright3dd60e22019-03-27 22:06:44 +00004927 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004928 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004929 const std::vector<Monitor>& monitors = it.second;
4930 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4931 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932 }
4933 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004934 const std::vector<Monitor>& monitors = it.second;
4935 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4936 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004939 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 }
4941
4942 nsecs_t currentTime = now();
4943
4944 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004945 if (!mRecentQueue.empty()) {
4946 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004947 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004948 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004949 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004950 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
4952 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004953 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954 }
4955
4956 // Dump event currently being dispatched.
4957 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004958 dump += INDENT "PendingEvent:\n";
4959 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004960 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004961 dump += StringPrintf(", age=%" PRId64 "ms\n",
4962 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004964 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965 }
4966
4967 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004968 if (!mInboundQueue.empty()) {
4969 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004970 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004971 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004972 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004973 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 }
4975 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004976 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 }
4978
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004979 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004980 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004981 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4982 const KeyReplacement& replacement = pair.first;
4983 int32_t newKeyCode = pair.second;
4984 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004985 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004986 }
4987 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004988 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004989 }
4990
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004991 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004992 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004993 for (const auto& pair : mConnectionsByFd) {
4994 const sp<Connection>& connection = pair.second;
4995 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004996 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004997 pair.first, connection->getInputChannelName().c_str(),
4998 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005001 if (!connection->outboundQueue.empty()) {
5002 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5003 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005004 dump += dumpQueue(connection->outboundQueue, currentTime);
5005
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005007 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 }
5009
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005010 if (!connection->waitQueue.empty()) {
5011 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5012 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005013 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005015 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016 }
5017 }
5018 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005019 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020 }
5021
5022 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005023 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5024 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005026 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 }
5028
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005029 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005030 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5031 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5032 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033}
5034
Michael Wright3dd60e22019-03-27 22:06:44 +00005035void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5036 const size_t numMonitors = monitors.size();
5037 for (size_t i = 0; i < numMonitors; i++) {
5038 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005039 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005040 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5041 dump += "\n";
5042 }
5043}
5044
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005045Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005046#if DEBUG_CHANNEL_CREATION
5047 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048#endif
5049
Garfield Tan15601662020-09-22 15:32:38 -07005050 std::shared_ptr<InputChannel> serverChannel;
5051 std::unique_ptr<InputChannel> clientChannel;
5052 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5053
5054 if (result) {
5055 return base::Error(result) << "Failed to open input channel pair with name " << name;
5056 }
5057
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005059 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07005060 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061
Garfield Tan15601662020-09-22 15:32:38 -07005062 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005063 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005064 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
5067 } // release lock
5068
5069 // Wake the looper because some connections have changed.
5070 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005071 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072}
5073
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005074Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5075 bool isGestureMonitor,
5076 const std::string& name,
5077 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005078 std::shared_ptr<InputChannel> serverChannel;
5079 std::unique_ptr<InputChannel> clientChannel;
5080 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5081 if (result) {
5082 return base::Error(result) << "Failed to open input channel pair with name " << name;
5083 }
5084
Michael Wright3dd60e22019-03-27 22:06:44 +00005085 { // acquire lock
5086 std::scoped_lock _l(mLock);
5087
5088 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005089 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5090 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005091 }
5092
Garfield Tan15601662020-09-22 15:32:38 -07005093 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00005094
Garfield Tan15601662020-09-22 15:32:38 -07005095 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005096 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005097 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005098
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005099 auto& monitorsByDisplay =
5100 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005101 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005102
5103 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00005104 }
Garfield Tan15601662020-09-22 15:32:38 -07005105
Michael Wright3dd60e22019-03-27 22:06:44 +00005106 // Wake the looper because some connections have changed.
5107 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005108 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005109}
5110
Garfield Tan15601662020-09-22 15:32:38 -07005111status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005113 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114
Garfield Tan15601662020-09-22 15:32:38 -07005115 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 if (status) {
5117 return status;
5118 }
5119 } // release lock
5120
5121 // Wake the poll loop because removing the connection may have changed the current
5122 // synchronization state.
5123 mLooper->wake();
5124 return OK;
5125}
5126
Garfield Tan15601662020-09-22 15:32:38 -07005127status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5128 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005129 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005130 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005131 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 return BAD_VALUE;
5133 }
5134
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005135 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005136 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005137
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005139 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 }
5141
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005142 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143
5144 nsecs_t currentTime = now();
5145 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5146
5147 connection->status = Connection::STATUS_ZOMBIE;
5148 return OK;
5149}
5150
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005151void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5152 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5153 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005154}
5155
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005157 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005158 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005159 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005160 std::vector<Monitor>& monitors = it->second;
5161 const size_t numMonitors = monitors.size();
5162 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005163 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005164 monitors.erase(monitors.begin() + i);
5165 break;
5166 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005167 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005168 if (monitors.empty()) {
5169 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005170 } else {
5171 ++it;
5172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174}
5175
Michael Wright3dd60e22019-03-27 22:06:44 +00005176status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5177 { // acquire lock
5178 std::scoped_lock _l(mLock);
5179 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5180
5181 if (!foundDisplayId) {
5182 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5183 return BAD_VALUE;
5184 }
5185 int32_t displayId = foundDisplayId.value();
5186
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005187 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5188 mTouchStatesByDisplay.find(displayId);
5189 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005190 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5191 return BAD_VALUE;
5192 }
5193
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005194 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005195 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005196 std::optional<int32_t> foundDeviceId;
5197 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005198 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005199 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005200 foundDeviceId = state.deviceId;
5201 }
5202 }
5203 if (!foundDeviceId || !state.down) {
5204 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005205 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005206 return BAD_VALUE;
5207 }
5208 int32_t deviceId = foundDeviceId.value();
5209
5210 // Send cancel events to all the input channels we're stealing from.
5211 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005212 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005213 options.deviceId = deviceId;
5214 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005215 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005216 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005217 std::shared_ptr<InputChannel> channel =
5218 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005219 if (channel != nullptr) {
5220 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005221 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005222 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005223 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005224 canceledWindows += "]";
5225 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5226 canceledWindows.c_str());
5227
Michael Wright3dd60e22019-03-27 22:06:44 +00005228 // Then clear the current touch state so we stop dispatching to them as well.
5229 state.filterNonMonitors();
5230 }
5231 return OK;
5232}
5233
Prabir Pradhan99987712020-11-10 18:43:05 -08005234void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5235 { // acquire lock
5236 std::scoped_lock _l(mLock);
5237 if (DEBUG_FOCUS) {
5238 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5239 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5240 windowHandle != nullptr ? windowHandle->getName().c_str()
5241 : "token without window");
5242 }
5243
Vishnu Nairc519ff72021-01-21 08:23:08 -08005244 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005245 if (focusedToken != windowToken) {
5246 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5247 enabled ? "enable" : "disable");
5248 return;
5249 }
5250
5251 if (enabled == mFocusedWindowRequestedPointerCapture) {
5252 ALOGW("Ignoring request to %s Pointer Capture: "
5253 "window has %s requested pointer capture.",
5254 enabled ? "enable" : "disable", enabled ? "already" : "not");
5255 return;
5256 }
5257
5258 mFocusedWindowRequestedPointerCapture = enabled;
5259 setPointerCaptureLocked(enabled);
5260 } // release lock
5261
5262 // Wake the thread to process command entries.
5263 mLooper->wake();
5264}
5265
Michael Wright3dd60e22019-03-27 22:06:44 +00005266std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5267 const sp<IBinder>& token) {
5268 for (const auto& it : mGestureMonitorsByDisplay) {
5269 const std::vector<Monitor>& monitors = it.second;
5270 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005271 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005272 return it.first;
5273 }
5274 }
5275 }
5276 return std::nullopt;
5277}
5278
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005279std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5280 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5281 if (gesturePid.has_value()) {
5282 return gesturePid;
5283 }
5284 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5285}
5286
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005287sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005288 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005289 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005290 }
5291
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005292 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005293 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005294 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005295 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 }
5297 }
Robert Carr4e670e52018-08-15 13:26:12 -07005298
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005299 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300}
5301
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005302std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5303 sp<Connection> connection = getConnectionLocked(connectionToken);
5304 if (connection == nullptr) {
5305 return "<nullptr>";
5306 }
5307 return connection->getInputChannelName();
5308}
5309
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005310void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005311 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005312 removeByValue(mConnectionsByFd, connection);
5313}
5314
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005315void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5316 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005317 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005318 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5319 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 commandEntry->connection = connection;
5321 commandEntry->eventTime = currentTime;
5322 commandEntry->seq = seq;
5323 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005324 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005325 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326}
5327
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005328void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5329 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005331 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005333 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5334 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005336 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337}
5338
Vishnu Nairad321cd2020-08-20 16:40:21 -07005339void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5340 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005341 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5342 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005343 commandEntry->oldToken = oldToken;
5344 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005345 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005346}
5347
arthurhungf452d0b2021-01-06 00:19:52 +08005348void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5349 std::unique_ptr<CommandEntry> commandEntry =
5350 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5351 commandEntry->newToken = token;
5352 commandEntry->x = x;
5353 commandEntry->y = y;
5354 postCommandLocked(std::move(commandEntry));
5355}
5356
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005357void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5358 if (connection == nullptr) {
5359 LOG_ALWAYS_FATAL("Caller must check for nullness");
5360 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005361 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5362 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005363 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005364 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005365 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005366 return;
5367 }
5368 /**
5369 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5370 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5371 * has changed. This could cause newer entries to time out before the already dispatched
5372 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5373 * processes the events linearly. So providing information about the oldest entry seems to be
5374 * most useful.
5375 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005376 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005377 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5378 std::string reason =
5379 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005380 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005381 ns2ms(currentWait),
5382 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005383 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005384 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005385
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005386 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5387
5388 // Stop waking up for events on this connection, it is already unresponsive
5389 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005390}
5391
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005392void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5393 std::string reason =
5394 StringPrintf("%s does not have a focused window", application->getName().c_str());
5395 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005396
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005397 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5398 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5399 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005400 postCommandLocked(std::move(commandEntry));
5401}
5402
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005403void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5404 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5405 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5406 commandEntry->obscuringPackage = obscuringPackage;
5407 postCommandLocked(std::move(commandEntry));
5408}
5409
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005410void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5411 const std::string& reason) {
5412 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5413 updateLastAnrStateLocked(windowLabel, reason);
5414}
5415
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005416void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5417 const std::string& reason) {
5418 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005419 updateLastAnrStateLocked(windowLabel, reason);
5420}
5421
5422void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5423 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005425 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 struct tm tm;
5427 localtime_r(&t, &tm);
5428 char timestr[64];
5429 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005430 mLastAnrState.clear();
5431 mLastAnrState += INDENT "ANR:\n";
5432 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005433 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5434 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005435 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436}
5437
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005438void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 mLock.unlock();
5440
5441 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5442
5443 mLock.lock();
5444}
5445
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005446void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 sp<Connection> connection = commandEntry->connection;
5448
5449 if (connection->status != Connection::STATUS_ZOMBIE) {
5450 mLock.unlock();
5451
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005452 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453
5454 mLock.lock();
5455 }
5456}
5457
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005458void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005459 sp<IBinder> oldToken = commandEntry->oldToken;
5460 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005461 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005462 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005463 mLock.lock();
5464}
5465
arthurhungf452d0b2021-01-06 00:19:52 +08005466void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5467 sp<IBinder> newToken = commandEntry->newToken;
5468 mLock.unlock();
5469 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5470 mLock.lock();
5471}
5472
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005473void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005475
5476 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5477
5478 mLock.lock();
5479}
5480
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005481void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005482 mLock.unlock();
5483
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005484 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
5486 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005487}
5488
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005489void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005490 mLock.unlock();
5491
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005492 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5493
5494 mLock.lock();
5495}
5496
5497void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5498 mLock.unlock();
5499
5500 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5501
5502 mLock.lock();
5503}
5504
5505void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5506 mLock.unlock();
5507
5508 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005509
5510 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005511}
5512
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005513void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5514 mLock.unlock();
5515
5516 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5517
5518 mLock.lock();
5519}
5520
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5522 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005523 KeyEntry& entry = *(commandEntry->keyEntry);
5524 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525
5526 mLock.unlock();
5527
Michael Wright2b3c3302018-03-02 17:19:13 +00005528 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005529 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005530 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005531 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5532 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005533 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535
5536 mLock.lock();
5537
5538 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005539 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005541 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005543 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5544 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546}
5547
chaviwfd6d3512019-03-25 13:23:49 -07005548void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5549 mLock.unlock();
5550 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5551 mLock.lock();
5552}
5553
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005554/**
5555 * Connection is responsive if it has no events in the waitQueue that are older than the
5556 * current time.
5557 */
5558static bool isConnectionResponsive(const Connection& connection) {
5559 const nsecs_t currentTime = now();
5560 for (const DispatchEntry* entry : connection.waitQueue) {
5561 if (entry->timeoutTime < currentTime) {
5562 return false;
5563 }
5564 }
5565 return true;
5566}
5567
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005568void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005570 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005572 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573
5574 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005575 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005576 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005577 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005579 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005580 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005581 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005582 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5583 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005584 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005585 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005586
5587 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005588 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005589 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005590 restartEvent =
5591 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005592 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005593 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005594 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5595 handled);
5596 } else {
5597 restartEvent = false;
5598 }
5599
5600 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005601 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005602 // contents of the wait queue to have been drained, so we need to double-check
5603 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005604 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5605 if (dispatchEntryIt != connection->waitQueue.end()) {
5606 dispatchEntry = *dispatchEntryIt;
5607 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005608 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5609 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005610 if (!connection->responsive) {
5611 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005612 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005613 // The connection was unresponsive, and now it's responsive.
5614 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005615 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005616 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005617 traceWaitQueueLength(connection);
5618 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005619 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005620 traceOutboundQueueLength(connection);
5621 } else {
5622 releaseDispatchEntry(dispatchEntry);
5623 }
5624 }
5625
5626 // Start the next dispatch cycle for this connection.
5627 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628}
5629
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005630void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5631 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5632 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5633 monitorUnresponsiveCommand->pid = pid;
5634 monitorUnresponsiveCommand->reason = std::move(reason);
5635 postCommandLocked(std::move(monitorUnresponsiveCommand));
5636}
5637
5638void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5639 std::string reason) {
5640 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5641 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5642 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5643 windowUnresponsiveCommand->reason = std::move(reason);
5644 postCommandLocked(std::move(windowUnresponsiveCommand));
5645}
5646
5647void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5648 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5649 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5650 monitorResponsiveCommand->pid = pid;
5651 postCommandLocked(std::move(monitorResponsiveCommand));
5652}
5653
5654void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5655 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5656 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5657 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5658 postCommandLocked(std::move(windowResponsiveCommand));
5659}
5660
5661/**
5662 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5663 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5664 * command entry to the command queue.
5665 */
5666void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5667 std::string reason) {
5668 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5669 if (connection.monitor) {
5670 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5671 reason.c_str());
5672 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5673 if (!pid.has_value()) {
5674 ALOGE("Could not find unresponsive monitor for connection %s",
5675 connection.inputChannel->getName().c_str());
5676 return;
5677 }
5678 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5679 return;
5680 }
5681 // If not a monitor, must be a window
5682 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5683 reason.c_str());
5684 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5685}
5686
5687/**
5688 * Tell the policy that a connection has become responsive so that it can stop ANR.
5689 */
5690void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5691 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5692 if (connection.monitor) {
5693 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5694 if (!pid.has_value()) {
5695 ALOGE("Could not find responsive monitor for connection %s",
5696 connection.inputChannel->getName().c_str());
5697 return;
5698 }
5699 sendMonitorResponsiveCommandLocked(pid.value());
5700 return;
5701 }
5702 // If not a monitor, must be a window
5703 sendWindowResponsiveCommandLocked(connectionToken);
5704}
5705
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005707 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005708 KeyEntry& keyEntry, bool handled) {
5709 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005710 if (!handled) {
5711 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005712 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005713 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005714 return false;
5715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005717 // Get the fallback key state.
5718 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005719 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005720 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005721 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005722 connection->inputState.removeFallbackKey(originalKeyCode);
5723 }
5724
5725 if (handled || !dispatchEntry->hasForegroundTarget()) {
5726 // If the application handles the original key for which we previously
5727 // generated a fallback or if the window is not a foreground window,
5728 // then cancel the associated fallback key, if any.
5729 if (fallbackKeyCode != -1) {
5730 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005732 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005733 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005734 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005736 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005737 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738
5739 mLock.unlock();
5740
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005741 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005742 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743
5744 mLock.lock();
5745
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005746 // Cancel the fallback key.
5747 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005749 "application handled the original non-fallback key "
5750 "or is no longer a foreground target, "
5751 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 options.keyCode = fallbackKeyCode;
5753 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005755 connection->inputState.removeFallbackKey(originalKeyCode);
5756 }
5757 } else {
5758 // If the application did not handle a non-fallback key, first check
5759 // that we are in a good state to perform unhandled key event processing
5760 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005761 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005762 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005764 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005765 "since this is not an initial down. "
5766 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005767 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005769 return false;
5770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005772 // Dispatch the unhandled key to the policy.
5773#if DEBUG_OUTBOUND_EVENT_DETAILS
5774 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005775 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005776 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005777#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005778 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005779
5780 mLock.unlock();
5781
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005782 bool fallback =
5783 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005784 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005785
5786 mLock.lock();
5787
5788 if (connection->status != Connection::STATUS_NORMAL) {
5789 connection->inputState.removeFallbackKey(originalKeyCode);
5790 return false;
5791 }
5792
5793 // Latch the fallback keycode for this key on an initial down.
5794 // The fallback keycode cannot change at any other point in the lifecycle.
5795 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005796 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005797 fallbackKeyCode = event.getKeyCode();
5798 } else {
5799 fallbackKeyCode = AKEYCODE_UNKNOWN;
5800 }
5801 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5802 }
5803
5804 ALOG_ASSERT(fallbackKeyCode != -1);
5805
5806 // Cancel the fallback key if the policy decides not to send it anymore.
5807 // We will continue to dispatch the key to the policy but we will no
5808 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005809 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5810 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005811#if DEBUG_OUTBOUND_EVENT_DETAILS
5812 if (fallback) {
5813 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005814 "as a fallback for %d, but on the DOWN it had requested "
5815 "to send %d instead. Fallback canceled.",
5816 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005817 } else {
5818 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005819 "but on the DOWN it had requested to send %d. "
5820 "Fallback canceled.",
5821 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005822 }
5823#endif
5824
5825 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5826 "canceling fallback, policy no longer desires it");
5827 options.keyCode = fallbackKeyCode;
5828 synthesizeCancelationEventsForConnectionLocked(connection, options);
5829
5830 fallback = false;
5831 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005832 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005833 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005834 }
5835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836
5837#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005838 {
5839 std::string msg;
5840 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5841 connection->inputState.getFallbackKeys();
5842 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005843 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005845 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005846 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005847 }
5848#endif
5849
5850 if (fallback) {
5851 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005852 keyEntry.eventTime = event.getEventTime();
5853 keyEntry.deviceId = event.getDeviceId();
5854 keyEntry.source = event.getSource();
5855 keyEntry.displayId = event.getDisplayId();
5856 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5857 keyEntry.keyCode = fallbackKeyCode;
5858 keyEntry.scanCode = event.getScanCode();
5859 keyEntry.metaState = event.getMetaState();
5860 keyEntry.repeatCount = event.getRepeatCount();
5861 keyEntry.downTime = event.getDownTime();
5862 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005863
5864#if DEBUG_OUTBOUND_EVENT_DETAILS
5865 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005866 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005867 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005868#endif
5869 return true; // restart the event
5870 } else {
5871#if DEBUG_OUTBOUND_EVENT_DETAILS
5872 ALOGD("Unhandled key event: No fallback key.");
5873#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005874
5875 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005876 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 }
5878 }
5879 return false;
5880}
5881
5882bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005883 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005884 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 return false;
5886}
5887
5888void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5889 mLock.unlock();
5890
Sean Stoutb4e0a592021-02-23 07:34:53 -08005891 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
5892 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893
5894 mLock.lock();
5895}
5896
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005897void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5898 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005899 // TODO Write some statistics about how long we spend waiting.
5900}
5901
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005902/**
5903 * Report the touch event latency to the statsd server.
5904 * Input events are reported for statistics if:
5905 * - This is a touchscreen event
5906 * - InputFilter is not enabled
5907 * - Event is not injected or synthesized
5908 *
5909 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5910 * from getting aggregated with the "old" data.
5911 */
5912void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5913 REQUIRES(mLock) {
5914 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5915 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5916 if (!reportForStatistics) {
5917 return;
5918 }
5919
5920 if (mTouchStatistics.shouldReport()) {
5921 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5922 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5923 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5924 mTouchStatistics.reset();
5925 }
5926 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5927 mTouchStatistics.addValue(latencyMicros);
5928}
5929
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930void InputDispatcher::traceInboundQueueLengthLocked() {
5931 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005932 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 }
5934}
5935
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005936void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 if (ATRACE_ENABLED()) {
5938 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005939 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005940 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 }
5942}
5943
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005944void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 if (ATRACE_ENABLED()) {
5946 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005947 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005948 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 }
5950}
5951
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005952void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005953 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005955 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 dumpDispatchStateLocked(dump);
5957
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005958 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005959 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005960 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 }
5962}
5963
5964void InputDispatcher::monitor() {
5965 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005966 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005968 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005969}
5970
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005971/**
5972 * Wake up the dispatcher and wait until it processes all events and commands.
5973 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5974 * this method can be safely called from any thread, as long as you've ensured that
5975 * the work you are interested in completing has already been queued.
5976 */
5977bool InputDispatcher::waitForIdle() {
5978 /**
5979 * Timeout should represent the longest possible time that a device might spend processing
5980 * events and commands.
5981 */
5982 constexpr std::chrono::duration TIMEOUT = 100ms;
5983 std::unique_lock lock(mLock);
5984 mLooper->wake();
5985 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5986 return result == std::cv_status::no_timeout;
5987}
5988
Vishnu Naire798b472020-07-23 13:52:21 -07005989/**
5990 * Sets focus to the window identified by the token. This must be called
5991 * after updating any input window handles.
5992 *
5993 * Params:
5994 * request.token - input channel token used to identify the window that should gain focus.
5995 * request.focusedToken - the token that the caller expects currently to be focused. If the
5996 * specified token does not match the currently focused window, this request will be dropped.
5997 * If the specified focused token matches the currently focused window, the call will succeed.
5998 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5999 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6000 * when requesting the focus change. This determines which request gets
6001 * precedence if there is a focus change request from another source such as pointer down.
6002 */
Vishnu Nair958da932020-08-21 17:12:37 -07006003void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6004 { // acquire lock
6005 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006006 std::optional<FocusResolver::FocusChanges> changes =
6007 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6008 if (changes) {
6009 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006010 }
6011 } // release lock
6012 // Wake up poll loop since it may need to make new input dispatching choices.
6013 mLooper->wake();
6014}
6015
Vishnu Nairc519ff72021-01-21 08:23:08 -08006016void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6017 if (changes.oldFocus) {
6018 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006019 if (focusedInputChannel) {
6020 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6021 "focus left window");
6022 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006023 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006024 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006025 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006026 if (changes.newFocus) {
6027 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006028 }
6029
Prabir Pradhan99987712020-11-10 18:43:05 -08006030 // If a window has pointer capture, then it must have focus. We need to ensure that this
6031 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6032 // If the window loses focus before it loses pointer capture, then the window can be in a state
6033 // where it has pointer capture but not focus, violating the contract. Therefore we must
6034 // dispatch the pointer capture event before the focus event. Since focus events are added to
6035 // the front of the queue (above), we add the pointer capture event to the front of the queue
6036 // after the focus events are added. This ensures the pointer capture event ends up at the
6037 // front.
6038 disablePointerCaptureForcedLocked();
6039
Vishnu Nairc519ff72021-01-21 08:23:08 -08006040 if (mFocusedDisplayId == changes.displayId) {
6041 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006042 }
6043}
Vishnu Nair958da932020-08-21 17:12:37 -07006044
Prabir Pradhan99987712020-11-10 18:43:05 -08006045void InputDispatcher::disablePointerCaptureForcedLocked() {
6046 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6047 return;
6048 }
6049
6050 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6051
6052 if (mFocusedWindowRequestedPointerCapture) {
6053 mFocusedWindowRequestedPointerCapture = false;
6054 setPointerCaptureLocked(false);
6055 }
6056
6057 if (!mWindowTokenWithPointerCapture) {
6058 // No need to send capture changes because no window has capture.
6059 return;
6060 }
6061
6062 if (mPendingEvent != nullptr) {
6063 // Move the pending event to the front of the queue. This will give the chance
6064 // for the pending event to be dropped if it is a captured event.
6065 mInboundQueue.push_front(mPendingEvent);
6066 mPendingEvent = nullptr;
6067 }
6068
6069 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6070 false /* hasCapture */);
6071 mInboundQueue.push_front(std::move(entry));
6072}
6073
Prabir Pradhan99987712020-11-10 18:43:05 -08006074void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6075 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6076 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6077 commandEntry->enabled = enabled;
6078 postCommandLocked(std::move(commandEntry));
6079}
6080
6081void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6082 android::inputdispatcher::CommandEntry* commandEntry) {
6083 mLock.unlock();
6084
6085 mPolicy->setPointerCapture(commandEntry->enabled);
6086
6087 mLock.lock();
6088}
6089
Garfield Tane84e6f92019-08-29 17:28:41 -07006090} // namespace android::inputdispatcher