blob: 43a861e126658693240fe2bdf7f0ae0b5f3aeb0c [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
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -070050#include <InputFlingerProperties.sysprop.h>
Michael Wright2b3c3302018-03-02 17:19:13 +000051#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080052#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050054#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070055#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100056#include <binder/IServiceManager.h>
57#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080058#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010059#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000061#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070062#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010063#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wright44753b12020-07-08 13:48:11 +010066#include <cerrno>
67#include <cinttypes>
68#include <climits>
69#include <cstddef>
70#include <ctime>
71#include <queue>
72#include <sstream>
73
74#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070075#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010076
Michael Wrightd02c5b62014-02-10 15:10:22 -080077#define INDENT " "
78#define INDENT2 " "
79#define INDENT3 " "
80#define INDENT4 " "
81
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000083using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080084using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080085using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080087using android::os::InputEventInjectionResult;
88using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100089using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080090
Garfield Tane84e6f92019-08-29 17:28:41 -070091namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Prabir Pradhan93a0f912021-04-21 13:47:42 -070093// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
94// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
95static bool isPerWindowInputRotationEnabled() {
96 static const bool PER_WINDOW_INPUT_ROTATION =
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -070097 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
98
Prabir Pradhan93a0f912021-04-21 13:47:42 -070099 return PER_WINDOW_INPUT_ROTATION;
100}
101
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102// Default input dispatching timeout if there is no focused application or paused window
103// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800104const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
105 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
106 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107
108// Amount of time to allow for all pending events to be processed when an app switch
109// key is on the way. This is used to preempt input dispatch and drop input events
110// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000111constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
113// Amount of time to allow for an event to be dispatched (measured since its eventTime)
114// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000115constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800116
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117// 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 +0000118constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
119
120// Log a warning when an interception call takes longer than this to process.
121constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700123// Additional key latency in case a connection is still processing some motion events.
124// This will help with the case when a user touched a button that opens a new window,
125// and gives us the chance to dispatch the key to this new window.
126constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
127
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000129constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
130
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000131// Event log tags. See EventLogTags.logtags for reference
132constexpr int LOGTAG_INPUT_INTERACTION = 62000;
133constexpr int LOGTAG_INPUT_FOCUS = 62001;
134
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135static inline nsecs_t now() {
136 return systemTime(SYSTEM_TIME_MONOTONIC);
137}
138
139static inline const char* toString(bool value) {
140 return value ? "true" : "false";
141}
142
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000143static inline const std::string toString(sp<IBinder> binder) {
144 if (binder == nullptr) {
145 return "<null>";
146 }
147 return StringPrintf("%p", binder.get());
148}
149
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700151 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
152 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153}
154
155static bool isValidKeyAction(int32_t action) {
156 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AKEY_EVENT_ACTION_DOWN:
158 case AKEY_EVENT_ACTION_UP:
159 return true;
160 default:
161 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 }
163}
164
165static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 ALOGE("Key event has invalid action code 0x%x", action);
168 return false;
169 }
170 return true;
171}
172
Michael Wright7b159c92015-05-14 14:48:03 +0100173static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800174 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 case AMOTION_EVENT_ACTION_DOWN:
176 case AMOTION_EVENT_ACTION_UP:
177 case AMOTION_EVENT_ACTION_CANCEL:
178 case AMOTION_EVENT_ACTION_MOVE:
179 case AMOTION_EVENT_ACTION_OUTSIDE:
180 case AMOTION_EVENT_ACTION_HOVER_ENTER:
181 case AMOTION_EVENT_ACTION_HOVER_MOVE:
182 case AMOTION_EVENT_ACTION_HOVER_EXIT:
183 case AMOTION_EVENT_ACTION_SCROLL:
184 return true;
185 case AMOTION_EVENT_ACTION_POINTER_DOWN:
186 case AMOTION_EVENT_ACTION_POINTER_UP: {
187 int32_t index = getMotionEventActionPointerIndex(action);
188 return index >= 0 && index < pointerCount;
189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
192 return actionButton != 0;
193 default:
194 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 }
196}
197
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500198static int64_t millis(std::chrono::nanoseconds t) {
199 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
200}
201
Michael Wright7b159c92015-05-14 14:48:03 +0100202static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700203 const PointerProperties* pointerProperties) {
204 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 ALOGE("Motion event has invalid action code 0x%x", action);
206 return false;
207 }
208 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000209 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700210 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 return false;
212 }
213 BitSet32 pointerIdBits;
214 for (size_t i = 0; i < pointerCount; i++) {
215 int32_t id = pointerProperties[i].id;
216 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700217 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
218 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 return false;
220 }
221 if (pointerIdBits.hasBit(id)) {
222 ALOGE("Motion event has duplicate pointer id %d", id);
223 return false;
224 }
225 pointerIdBits.markBit(id);
226 }
227 return true;
228}
229
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000230static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000232 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
234
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000235 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 bool first = true;
237 Region::const_iterator cur = region.begin();
238 Region::const_iterator const tail = region.end();
239 while (cur != tail) {
240 if (first) {
241 first = false;
242 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800243 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800245 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246 cur++;
247 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000248 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249}
250
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500251static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
252 constexpr size_t maxEntries = 50; // max events to print
253 constexpr size_t skipBegin = maxEntries / 2;
254 const size_t skipEnd = queue.size() - maxEntries / 2;
255 // skip from maxEntries / 2 ... size() - maxEntries/2
256 // only print from 0 .. skipBegin and then from skipEnd .. size()
257
258 std::string dump;
259 for (size_t i = 0; i < queue.size(); i++) {
260 const DispatchEntry& entry = *queue[i];
261 if (i >= skipBegin && i < skipEnd) {
262 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
263 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
264 continue;
265 }
266 dump.append(INDENT4);
267 dump += entry.eventEntry->getDescription();
268 dump += StringPrintf(", seq=%" PRIu32
269 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
270 entry.seq, entry.targetFlags, entry.resolvedAction,
271 ns2ms(currentTime - entry.eventEntry->eventTime));
272 if (entry.deliveryTime != 0) {
273 // This entry was delivered, so add information on how long we've been waiting
274 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
275 }
276 dump.append("\n");
277 }
278 return dump;
279}
280
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700281/**
282 * Find the entry in std::unordered_map by key, and return it.
283 * If the entry is not found, return a default constructed entry.
284 *
285 * Useful when the entries are vectors, since an empty vector will be returned
286 * if the entry is not found.
287 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
288 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700289template <typename K, typename V>
290static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700291 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700292 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800293}
294
chaviwaf87b3e2019-10-01 16:59:28 -0700295static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
296 if (first == second) {
297 return true;
298 }
299
300 if (first == nullptr || second == nullptr) {
301 return false;
302 }
303
304 return first->getToken() == second->getToken();
305}
306
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000307static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
308 if (first == nullptr || second == nullptr) {
309 return false;
310 }
311 return first->applicationInfo.token != nullptr &&
312 first->applicationInfo.token == second->applicationInfo.token;
313}
314
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800315static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
316 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
317}
318
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700320 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900322 if (eventEntry->type == EventEntry::Type::MOTION) {
323 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700324 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
325 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900326 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700327 // Use identity transform for joystick and position-based (touchpad) events because they
328 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900329 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700330 1.0f /*globalScaleFactor*/,
331 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900332 }
333 }
334
chaviw1ff3d1e2020-07-01 15:53:47 -0700335 if (inputTarget.useDefaultPointerTransform()) {
336 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700337 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700338 inputTarget.globalScaleFactor,
339 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000340 }
341
342 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
343 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
344
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700345 std::vector<PointerCoords> pointerCoords;
346 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000347
348 // Use the first pointer information to normalize all other pointers. This could be any pointer
349 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700350 // uses the transform for the normalized pointer.
351 const ui::Transform& firstPointerTransform =
352 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
353 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000354
355 // Iterate through all pointers in the event to normalize against the first.
356 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
357 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
358 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700359 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360
361 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700362 // First, apply the current pointer's transform to update the coordinates into
363 // window space.
364 pointerCoords[pointerIndex].transform(currTransform);
365 // Next, apply the inverse transform of the normalized coordinates so the
366 // current coordinates are transformed into the normalized coordinate space.
367 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000368 }
369
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700370 std::unique_ptr<MotionEntry> combinedMotionEntry =
371 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
372 motionEntry.deviceId, motionEntry.source,
373 motionEntry.displayId, motionEntry.policyFlags,
374 motionEntry.action, motionEntry.actionButton,
375 motionEntry.flags, motionEntry.metaState,
376 motionEntry.buttonState, motionEntry.classification,
377 motionEntry.edgeFlags, motionEntry.xPrecision,
378 motionEntry.yPrecision, motionEntry.xCursorPosition,
379 motionEntry.yCursorPosition, motionEntry.downTime,
380 motionEntry.pointerCount, motionEntry.pointerProperties,
381 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000382
383 if (motionEntry.injectionState) {
384 combinedMotionEntry->injectionState = motionEntry.injectionState;
385 combinedMotionEntry->injectionState->refCount += 1;
386 }
387
388 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700389 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700390 firstPointerTransform, inputTarget.globalScaleFactor,
391 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000392 return dispatchEntry;
393}
394
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700395static void addGestureMonitors(const std::vector<Monitor>& monitors,
396 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
397 float yOffset = 0) {
398 if (monitors.empty()) {
399 return;
400 }
401 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
402 for (const Monitor& monitor : monitors) {
403 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
404 }
405}
406
Garfield Tan15601662020-09-22 15:32:38 -0700407static status_t openInputChannelPair(const std::string& name,
408 std::shared_ptr<InputChannel>& serverChannel,
409 std::unique_ptr<InputChannel>& clientChannel) {
410 std::unique_ptr<InputChannel> uniqueServerChannel;
411 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
412
413 serverChannel = std::move(uniqueServerChannel);
414 return result;
415}
416
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500417template <typename T>
418static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
419 if (lhs == nullptr && rhs == nullptr) {
420 return true;
421 }
422 if (lhs == nullptr || rhs == nullptr) {
423 return false;
424 }
425 return *lhs == *rhs;
426}
427
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000428static sp<IPlatformCompatNative> getCompatService() {
429 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
430 if (service == nullptr) {
431 ALOGE("Failed to link to compat service");
432 return nullptr;
433 }
434 return interface_cast<IPlatformCompatNative>(service);
435}
436
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000437static KeyEvent createKeyEvent(const KeyEntry& entry) {
438 KeyEvent event;
439 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
440 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
441 entry.repeatCount, entry.downTime, entry.eventTime);
442 return event;
443}
444
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000445static std::optional<int32_t> findMonitorPidByToken(
446 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
447 const sp<IBinder>& token) {
448 for (const auto& it : monitorsByDisplay) {
449 const std::vector<Monitor>& monitors = it.second;
450 for (const Monitor& monitor : monitors) {
451 if (monitor.inputChannel->getConnectionToken() == token) {
452 return monitor.pid;
453 }
454 }
455 }
456 return std::nullopt;
457}
458
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000459static bool shouldReportMetricsForConnection(const Connection& connection) {
460 // Do not keep track of gesture monitors. They receive every event and would disproportionately
461 // affect the statistics.
462 if (connection.monitor) {
463 return false;
464 }
465 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
466 if (!connection.responsive) {
467 return false;
468 }
469 return true;
470}
471
472static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
473 const Connection& connection) {
474 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
475 const int32_t& inputEventId = eventEntry.id;
476 if (inputEventId != dispatchEntry.resolvedEventId) {
477 // Event was transmuted
478 return false;
479 }
480 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
481 return false;
482 }
483 // Only track latency for events that originated from hardware
484 if (eventEntry.isSynthesized()) {
485 return false;
486 }
487 const EventEntry::Type& inputEventEntryType = eventEntry.type;
488 if (inputEventEntryType == EventEntry::Type::KEY) {
489 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
490 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
491 return false;
492 }
493 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
494 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
495 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
496 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
497 return false;
498 }
499 } else {
500 // Not a key or a motion
501 return false;
502 }
503 if (!shouldReportMetricsForConnection(connection)) {
504 return false;
505 }
506 return true;
507}
508
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509// --- InputDispatcher ---
510
Garfield Tan00f511d2019-06-12 16:55:40 -0700511InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
512 : mPolicy(policy),
513 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700514 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800515 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700516 mAppSwitchSawKeyDown(false),
517 mAppSwitchDueTime(LONG_LONG_MAX),
518 mNextUnblockedEvent(nullptr),
519 mDispatchEnabled(false),
520 mDispatchFrozen(false),
521 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800522 // mInTouchMode will be initialized by the WindowManager to the default device config.
523 // To avoid leaking stack in case that call never comes, and for tests,
524 // initialize it here anyways.
525 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100526 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000527 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800528 mFocusedWindowRequestedPointerCapture(false),
529 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000530 mLatencyAggregator(),
531 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000532 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800534 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535
Yi Kong9b14ac62018-07-17 13:48:38 -0700536 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537
538 policy->getDispatcherConfiguration(&mConfig);
539}
540
541InputDispatcher::~InputDispatcher() {
542 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800543 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544
545 resetKeyRepeatLocked();
546 releasePendingEventLocked();
547 drainInboundQueueLocked();
548 }
549
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000550 while (!mConnectionsByToken.empty()) {
551 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700552 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 }
554}
555
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700556status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700557 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700558 return ALREADY_EXISTS;
559 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700560 mThread = std::make_unique<InputThread>(
561 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
562 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700563}
564
565status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700566 if (mThread && mThread->isCallingThread()) {
567 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700568 return INVALID_OPERATION;
569 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700570 mThread.reset();
571 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700572}
573
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574void InputDispatcher::dispatchOnce() {
575 nsecs_t nextWakeupTime = LONG_LONG_MAX;
576 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800577 std::scoped_lock _l(mLock);
578 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
580 // Run a dispatch loop if there are no pending commands.
581 // The dispatch loop might enqueue commands to run afterwards.
582 if (!haveCommandsLocked()) {
583 dispatchOnceInnerLocked(&nextWakeupTime);
584 }
585
586 // Run all pending commands if there are any.
587 // If any commands were run then force the next poll to wake up immediately.
588 if (runCommandsLockedInterruptible()) {
589 nextWakeupTime = LONG_LONG_MIN;
590 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800591
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700592 // If we are still waiting for ack on some events,
593 // we might have to wake up earlier to check if an app is anr'ing.
594 const nsecs_t nextAnrCheck = processAnrsLocked();
595 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
596
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800597 // We are about to enter an infinitely long sleep, because we have no commands or
598 // pending or queued events
599 if (nextWakeupTime == LONG_LONG_MAX) {
600 mDispatcherEnteredIdle.notify_all();
601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 } // release lock
603
604 // Wait for callback or timeout or wake. (make sure we round up, not down)
605 nsecs_t currentTime = now();
606 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
607 mLooper->pollOnce(timeoutMillis);
608}
609
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700610/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500611 * Raise ANR if there is no focused window.
612 * Before the ANR is raised, do a final state check:
613 * 1. The currently focused application must be the same one we are waiting for.
614 * 2. Ensure we still don't have a focused window.
615 */
616void InputDispatcher::processNoFocusedWindowAnrLocked() {
617 // Check if the application that we are waiting for is still focused.
618 std::shared_ptr<InputApplicationHandle> focusedApplication =
619 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
620 if (focusedApplication == nullptr ||
621 focusedApplication->getApplicationToken() !=
622 mAwaitedFocusedApplication->getApplicationToken()) {
623 // Unexpected because we should have reset the ANR timer when focused application changed
624 ALOGE("Waited for a focused window, but focused application has already changed to %s",
625 focusedApplication->getName().c_str());
626 return; // The focused application has changed.
627 }
628
629 const sp<InputWindowHandle>& focusedWindowHandle =
630 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
631 if (focusedWindowHandle != nullptr) {
632 return; // We now have a focused window. No need for ANR.
633 }
634 onAnrLocked(mAwaitedFocusedApplication);
635}
636
637/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638 * Check if any of the connections' wait queues have events that are too old.
639 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
640 * Return the time at which we should wake up next.
641 */
642nsecs_t InputDispatcher::processAnrsLocked() {
643 const nsecs_t currentTime = now();
644 nsecs_t nextAnrCheck = LONG_LONG_MAX;
645 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
646 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
647 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500648 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700649 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500650 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700651 return LONG_LONG_MIN;
652 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500653 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700654 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
655 }
656 }
657
658 // Check if any connection ANRs are due
659 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
660 if (currentTime < nextAnrCheck) { // most likely scenario
661 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
662 }
663
664 // If we reached here, we have an unresponsive connection.
665 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
666 if (connection == nullptr) {
667 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
668 return nextAnrCheck;
669 }
670 connection->responsive = false;
671 // Stop waking up for this unresponsive connection
672 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000673 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700674 return LONG_LONG_MIN;
675}
676
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500677std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 sp<InputWindowHandle> window = getWindowHandleLocked(token);
679 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500680 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700681 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500682 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700683}
684
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
686 nsecs_t currentTime = now();
687
Jeff Browndc5992e2014-04-11 01:27:26 -0700688 // Reset the key repeat timer whenever normal dispatch is suspended while the
689 // device is in a non-interactive state. This is to ensure that we abort a key
690 // repeat if the device is just coming out of sleep.
691 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 resetKeyRepeatLocked();
693 }
694
695 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
696 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100697 if (DEBUG_FOCUS) {
698 ALOGD("Dispatch frozen. Waiting some more.");
699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 return;
701 }
702
703 // Optimize latency of app switches.
704 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
705 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
706 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
707 if (mAppSwitchDueTime < *nextWakeupTime) {
708 *nextWakeupTime = mAppSwitchDueTime;
709 }
710
711 // Ready to start a new event.
712 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700714 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 if (isAppSwitchDue) {
716 // The inbound queue is empty so the app switch key we were waiting
717 // for will never arrive. Stop waiting for it.
718 resetPendingAppSwitchLocked(false);
719 isAppSwitchDue = false;
720 }
721
722 // Synthesize a key repeat if appropriate.
723 if (mKeyRepeatState.lastKeyEntry) {
724 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
725 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
726 } else {
727 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
728 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
729 }
730 }
731 }
732
733 // Nothing to do if there is no pending event.
734 if (!mPendingEvent) {
735 return;
736 }
737 } else {
738 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700739 mPendingEvent = mInboundQueue.front();
740 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 traceInboundQueueLengthLocked();
742 }
743
744 // Poke user activity for this event.
745 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700746 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 }
749
750 // Now we have an event to dispatch.
751 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700752 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700754 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700756 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700758 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 }
760
761 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700762 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 }
764
765 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700766 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700767 const ConfigurationChangedEntry& typedEntry =
768 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700770 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 break;
772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700774 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700775 const DeviceResetEntry& typedEntry =
776 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 break;
780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100782 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700783 std::shared_ptr<FocusEntry> typedEntry =
784 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100785 dispatchFocusLocked(currentTime, typedEntry);
786 done = true;
787 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
788 break;
789 }
790
Prabir Pradhan99987712020-11-10 18:43:05 -0800791 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
792 const auto typedEntry =
793 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
794 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
795 done = true;
796 break;
797 }
798
arthurhungb89ccb02020-12-30 16:19:01 +0800799 case EventEntry::Type::DRAG: {
800 std::shared_ptr<DragEntry> typedEntry =
801 std::static_pointer_cast<DragEntry>(mPendingEvent);
802 dispatchDragLocked(currentTime, typedEntry);
803 done = true;
804 break;
805 }
806
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700807 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700810 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 resetPendingAppSwitchLocked(true);
812 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700813 } else if (dropReason == DropReason::NOT_DROPPED) {
814 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 }
816 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700817 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700818 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700820 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
821 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 break;
825 }
826
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700827 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700828 std::shared_ptr<MotionEntry> motionEntry =
829 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700830 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
831 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700833 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700836 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
837 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700840 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 }
Chris Yef59a2f42020-10-16 12:55:26 -0700842
843 case EventEntry::Type::SENSOR: {
844 std::shared_ptr<SensorEntry> sensorEntry =
845 std::static_pointer_cast<SensorEntry>(mPendingEvent);
846 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
847 dropReason = DropReason::APP_SWITCH;
848 }
849 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
850 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
851 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
852 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
853 dropReason = DropReason::STALE;
854 }
855 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
856 done = true;
857 break;
858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 }
860
861 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700862 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700863 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 }
Michael Wright3a981722015-06-10 15:26:13 +0100865 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866
867 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 }
870}
871
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700872/**
873 * Return true if the events preceding this incoming motion event should be dropped
874 * Return false otherwise (the default behaviour)
875 */
876bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700878 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700879
880 // Optimize case where the current application is unresponsive and the user
881 // decides to touch a window in a different application.
882 // If the application takes too long to catch up then we drop all events preceding
883 // the touch into the other window.
884 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700885 int32_t displayId = motionEntry.displayId;
886 int32_t x = static_cast<int32_t>(
887 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
888 int32_t y = static_cast<int32_t>(
889 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
890 sp<InputWindowHandle> touchedWindowHandle =
891 findTouchedWindowAtLocked(displayId, x, y, nullptr);
892 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 touchedWindowHandle->getApplicationToken() !=
894 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700895 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700896 ALOGI("Pruning input queue because user touched a different application while waiting "
897 "for %s",
898 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700899 return true;
900 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700901
902 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600903 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700904 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
905 sp<Connection> connection =
906 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000907 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700908 // This monitor could take more input. Drop all events preceding this
909 // event, so that gesture monitor could get a chance to receive the stream
910 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
911 "responsive gesture monitor that may handle the event",
912 mAwaitedFocusedApplication->getName().c_str());
913 return true;
914 }
915 }
916 }
917
918 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
919 // yet been processed by some connections, the dispatcher will wait for these motion
920 // events to be processed before dispatching the key event. This is because these motion events
921 // may cause a new window to be launched, which the user might expect to receive focus.
922 // To prevent waiting forever for such events, just send the key to the currently focused window
923 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
924 ALOGD("Received a new pointer down event, stop waiting for events to process and "
925 "just send the pending key event to the focused window.");
926 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700927 }
928 return false;
929}
930
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700931bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700932 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700933 mInboundQueue.push_back(std::move(newEntry));
934 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 traceInboundQueueLengthLocked();
936
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700937 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700938 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 // Optimize app switch latency.
940 // If the application takes too long to catch up then we drop all events preceding
941 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700942 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700944 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700946 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700951 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 mAppSwitchSawKeyDown = false;
953 needWake = true;
954 }
955 }
956 }
957 break;
958 }
959
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700960 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700961 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
962 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700963 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700965 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100967 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700968 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
969 break;
970 }
971 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800972 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700973 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800974 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
975 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700976 // nothing to do
977 break;
978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980
981 return needWake;
982}
983
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700985 // Do not store sensor event in recent queue to avoid flooding the queue.
986 if (entry->type != EventEntry::Type::SENSOR) {
987 mRecentQueue.push_back(entry);
988 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700989 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 }
992}
993
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700995 int32_t y, TouchState* touchState,
996 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800997 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600998 if (addOutsideTargets && touchState == nullptr) {
999 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -07001002 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001003 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001004 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001005 continue;
1006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1008 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001009 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010
1011 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001012 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1013 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1014 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1016 // Found window.
1017 return windowHandle;
1018 }
1019 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001020
Michael Wright44753b12020-07-08 13:48:11 +01001021 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001022 touchState->addOrUpdateWindow(windowHandle,
1023 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1024 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 }
1028 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001029 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030}
1031
Garfield Tane84e6f92019-08-29 17:28:41 -07001032std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001033 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001034 std::vector<TouchedMonitor> touchedMonitors;
1035
1036 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1037 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001038 return touchedMonitors;
1039}
1040
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001041void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 const char* reason;
1043 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001044 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001046 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048 reason = "inbound event was dropped because the policy consumed it";
1049 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 case DropReason::DISABLED:
1051 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 ALOGI("Dropped event because input dispatch is disabled.");
1053 }
1054 reason = "inbound event was dropped because input dispatch is disabled";
1055 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001056 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 ALOGI("Dropped event because of pending overdue app switch.");
1058 reason = "inbound event was dropped because of pending overdue app switch";
1059 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001060 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 ALOGI("Dropped event because the current application is not responding and the user "
1062 "has started interacting with a different application.");
1063 reason = "inbound event was dropped because the current application is not responding "
1064 "and the user has started interacting with a different application";
1065 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 ALOGI("Dropped event because it is stale.");
1068 reason = "inbound event was dropped because it is stale";
1069 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001070 case DropReason::NO_POINTER_CAPTURE:
1071 ALOGI("Dropped event because there is no window with Pointer Capture.");
1072 reason = "inbound event was dropped because there is no window with Pointer Capture";
1073 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 case DropReason::NOT_DROPPED: {
1075 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 }
1079
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001080 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001081 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1083 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001087 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1088 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1090 synthesizeCancelationEventsForAllConnectionsLocked(options);
1091 } else {
1092 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1093 synthesizeCancelationEventsForAllConnectionsLocked(options);
1094 }
1095 break;
1096 }
Chris Yef59a2f42020-10-16 12:55:26 -07001097 case EventEntry::Type::SENSOR: {
1098 break;
1099 }
arthurhungb89ccb02020-12-30 16:19:01 +08001100 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1101 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001102 break;
1103 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001104 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001105 case EventEntry::Type::CONFIGURATION_CHANGED:
1106 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001107 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001108 break;
1109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 }
1111}
1112
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001113static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1115 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116}
1117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001118bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1119 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1120 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1121 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122}
1123
1124bool InputDispatcher::isAppSwitchPendingLocked() {
1125 return mAppSwitchDueTime != LONG_LONG_MAX;
1126}
1127
1128void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1129 mAppSwitchDueTime = LONG_LONG_MAX;
1130
1131#if DEBUG_APP_SWITCH
1132 if (handled) {
1133 ALOGD("App switch has arrived.");
1134 } else {
1135 ALOGD("App switch was abandoned.");
1136 }
1137#endif
1138}
1139
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001141 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142}
1143
1144bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001145 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 return false;
1147 }
1148
1149 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001150 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001151 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001153 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154
1155 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001156 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 return true;
1158}
1159
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001160void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1161 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162}
1163
1164void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001165 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001166 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001167 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 releaseInboundEventLocked(entry);
1169 }
1170 traceInboundQueueLengthLocked();
1171}
1172
1173void InputDispatcher::releasePendingEventLocked() {
1174 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001176 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
1178}
1179
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001180void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001182 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183#if DEBUG_DISPATCH_CYCLE
1184 ALOGD("Injected inbound event was dropped.");
1185#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001186 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 }
1188 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001189 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192}
1193
1194void InputDispatcher::resetKeyRepeatLocked() {
1195 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001196 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 }
1198}
1199
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1201 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202
Michael Wright2e732952014-09-24 13:26:59 -07001203 uint32_t policyFlags = entry->policyFlags &
1204 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001206 std::shared_ptr<KeyEntry> newEntry =
1207 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1208 entry->source, entry->displayId, policyFlags, entry->action,
1209 entry->flags, entry->keyCode, entry->scanCode,
1210 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001212 newEntry->syntheticRepeat = true;
1213 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216}
1217
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001218bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001219 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001221 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222#endif
1223
1224 // Reset key repeating in case a keyboard device was added or removed or something.
1225 resetKeyRepeatLocked();
1226
1227 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001228 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1229 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001230 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001231 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 return true;
1233}
1234
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1236 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1239 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240#endif
1241
liushenxiang42232912021-05-21 20:24:09 +08001242 // Reset key repeating in case a keyboard device was disabled or enabled.
1243 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1244 resetKeyRepeatLocked();
1245 }
1246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 synthesizeCancelationEventsForAllConnectionsLocked(options);
1250 return true;
1251}
1252
Vishnu Nairad321cd2020-08-20 16:40:21 -07001253void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001254 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001255 if (mPendingEvent != nullptr) {
1256 // Move the pending event to the front of the queue. This will give the chance
1257 // for the pending event to get dispatched to the newly focused window
1258 mInboundQueue.push_front(mPendingEvent);
1259 mPendingEvent = nullptr;
1260 }
1261
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262 std::unique_ptr<FocusEntry> focusEntry =
1263 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1264 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001265
1266 // This event should go to the front of the queue, but behind all other focus events
1267 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001269 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001270 [](const std::shared_ptr<EventEntry>& event) {
1271 return event->type == EventEntry::Type::FOCUS;
1272 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001273
1274 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001276}
1277
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001279 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001280 if (channel == nullptr) {
1281 return; // Window has gone away
1282 }
1283 InputTarget target;
1284 target.inputChannel = channel;
1285 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1286 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001287 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1288 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001289 std::string reason = std::string("reason=").append(entry->reason);
1290 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001291 dispatchEventLocked(currentTime, entry, {target});
1292}
1293
Prabir Pradhan99987712020-11-10 18:43:05 -08001294void InputDispatcher::dispatchPointerCaptureChangedLocked(
1295 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1296 DropReason& dropReason) {
1297 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001298 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1299 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1300 }
1301 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001302 // Pointer capture was already forcefully disabled because of focus change.
1303 dropReason = DropReason::NOT_DROPPED;
1304 return;
1305 }
1306
1307 // Set drop reason for early returns
1308 dropReason = DropReason::NO_POINTER_CAPTURE;
1309
1310 sp<IBinder> token;
1311 if (entry->pointerCaptureEnabled) {
1312 // Enable Pointer Capture
1313 if (!mFocusedWindowRequestedPointerCapture) {
1314 // This can happen if a window requests capture and immediately releases capture.
1315 ALOGW("No window requested Pointer Capture.");
1316 return;
1317 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001318 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001319 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1320 mWindowTokenWithPointerCapture = token;
1321 } else {
1322 // Disable Pointer Capture
1323 token = mWindowTokenWithPointerCapture;
1324 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001325 if (mFocusedWindowRequestedPointerCapture) {
1326 mFocusedWindowRequestedPointerCapture = false;
1327 setPointerCaptureLocked(false);
1328 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001329 }
1330
1331 auto channel = getInputChannelLocked(token);
1332 if (channel == nullptr) {
1333 // Window has gone away, clean up Pointer Capture state.
1334 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001335 if (mFocusedWindowRequestedPointerCapture) {
1336 mFocusedWindowRequestedPointerCapture = false;
1337 setPointerCaptureLocked(false);
1338 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001339 return;
1340 }
1341 InputTarget target;
1342 target.inputChannel = channel;
1343 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1344 entry->dispatchInProgress = true;
1345 dispatchEventLocked(currentTime, entry, {target});
1346
1347 dropReason = DropReason::NOT_DROPPED;
1348}
1349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001350bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001351 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 if (!entry->dispatchInProgress) {
1354 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1355 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1356 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1357 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001358 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 // We have seen two identical key downs in a row which indicates that the device
1360 // driver is automatically generating key repeats itself. We take note of the
1361 // repeat here, but we disable our own next key repeat timer since it is clear that
1362 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001363 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1364 // Make sure we don't get key down from a different device. If a different
1365 // device Id has same key pressed down, the new device Id will replace the
1366 // current one to hold the key repeat with repeat count reset.
1367 // In the future when got a KEY_UP on the device id, drop it and do not
1368 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1370 resetKeyRepeatLocked();
1371 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1372 } else {
1373 // Not a repeat. Save key down state in case we do see a repeat later.
1374 resetKeyRepeatLocked();
1375 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1376 }
1377 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001378 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1379 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001381#if DEBUG_INBOUND_EVENT_DETAILS
1382 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1383#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001384 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 resetKeyRepeatLocked();
1386 }
1387
1388 if (entry->repeatCount == 1) {
1389 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1390 } else {
1391 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1392 }
1393
1394 entry->dispatchInProgress = true;
1395
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001396 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 }
1398
1399 // Handle case where the policy asked us to try again later last time.
1400 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1401 if (currentTime < entry->interceptKeyWakeupTime) {
1402 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1403 *nextWakeupTime = entry->interceptKeyWakeupTime;
1404 }
1405 return false; // wait until next wakeup
1406 }
1407 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1408 entry->interceptKeyWakeupTime = 0;
1409 }
1410
1411 // Give the policy a chance to intercept the key.
1412 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1413 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001414 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001415 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001416 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001417 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001418 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001420 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 return false; // wait for the command to run
1422 } else {
1423 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1424 }
1425 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001426 if (*dropReason == DropReason::NOT_DROPPED) {
1427 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 }
1429 }
1430
1431 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001432 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001434 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1435 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001436 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 return true;
1438 }
1439
1440 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001441 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001442 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001443 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001444 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 return false;
1446 }
1447
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001448 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001449 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 return true;
1451 }
1452
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001453 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001454 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455
1456 // Dispatch the key.
1457 dispatchEventLocked(currentTime, entry, inputTargets);
1458 return true;
1459}
1460
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001461void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001463 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1465 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001466 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1467 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1468 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469#endif
1470}
1471
Chris Yef59a2f42020-10-16 12:55:26 -07001472void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1473 mLock.unlock();
1474
1475 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1476 if (entry->accuracyChanged) {
1477 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1478 }
1479 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1480 entry->hwTimestamp, entry->values);
1481 mLock.lock();
1482}
1483
1484void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1485 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1486#if DEBUG_OUTBOUND_EVENT_DETAILS
1487 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1488 "source=0x%x, sensorType=%s",
1489 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001490 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001491#endif
1492 std::unique_ptr<CommandEntry> commandEntry =
1493 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1494 commandEntry->sensorEntry = entry;
1495 postCommandLocked(std::move(commandEntry));
1496}
1497
1498bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1499#if DEBUG_OUTBOUND_EVENT_DETAILS
1500 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1501 NamedEnum::string(sensorType).c_str());
1502#endif
1503 { // acquire lock
1504 std::scoped_lock _l(mLock);
1505
1506 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1507 std::shared_ptr<EventEntry> entry = *it;
1508 if (entry->type == EventEntry::Type::SENSOR) {
1509 it = mInboundQueue.erase(it);
1510 releaseInboundEventLocked(entry);
1511 }
1512 }
1513 }
1514 return true;
1515}
1516
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001517bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001518 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001519 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001521 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 entry->dispatchInProgress = true;
1523
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001524 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
1526
1527 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001528 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001529 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001530 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1531 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return true;
1533 }
1534
1535 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1536
1537 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001538 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539
1540 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001541 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 if (isPointerEvent) {
1543 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001544 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001545 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001546 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 } else {
1548 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001549 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001550 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001552 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 return false;
1554 }
1555
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001556 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001558 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1559 return true;
1560 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001561 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001562 CancelationOptions::Mode mode(isPointerEvent
1563 ? CancelationOptions::CANCEL_POINTER_EVENTS
1564 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1565 CancelationOptions options(mode, "input event injection failed");
1566 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 return true;
1568 }
1569
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001570 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001571 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572
1573 // Dispatch the motion.
1574 if (conflictingPointerActions) {
1575 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 synthesizeCancelationEventsForAllConnectionsLocked(options);
1578 }
1579 dispatchEventLocked(currentTime, entry, inputTargets);
1580 return true;
1581}
1582
arthurhungb89ccb02020-12-30 16:19:01 +08001583void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1584 bool isExiting, const MotionEntry& motionEntry) {
1585 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1586 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1587 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1588 PointerCoords pointerCoords;
1589 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1590 pointerCoords.transform(windowHandle->getInfo()->transform);
1591
1592 std::unique_ptr<DragEntry> dragEntry =
1593 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1594 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1595 pointerCoords.getY());
1596
1597 enqueueInboundEventLocked(std::move(dragEntry));
1598}
1599
1600void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1601 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1602 if (channel == nullptr) {
1603 return; // Window has gone away
1604 }
1605 InputTarget target;
1606 target.inputChannel = channel;
1607 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1608 entry->dispatchInProgress = true;
1609 dispatchEventLocked(currentTime, entry, {target});
1610}
1611
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001614 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001615 ", policyFlags=0x%x, "
1616 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1617 "metaState=0x%x, buttonState=0x%x,"
1618 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001619 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1620 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1621 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001625 "x=%f, y=%f, pressure=%f, size=%f, "
1626 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1627 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001628 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1629 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1630 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1631 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1632 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1633 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1634 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1635 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1636 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1637 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 }
1639#endif
1640}
1641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001642void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1643 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001644 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001645 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646#if DEBUG_DISPATCH_CYCLE
1647 ALOGD("dispatchEventToCurrentInputTargets");
1648#endif
1649
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001650 updateInteractionTokensLocked(*eventEntry, inputTargets);
1651
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1653
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001656 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001657 sp<Connection> connection =
1658 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001659 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001660 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001662 if (DEBUG_FOCUS) {
1663 ALOGD("Dropping event delivery to target with channel '%s' because it "
1664 "is no longer registered with the input dispatcher.",
1665 inputTarget.inputChannel->getName().c_str());
1666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 }
1668 }
1669}
1670
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001671void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1672 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1673 // If the policy decides to close the app, we will get a channel removal event via
1674 // unregisterInputChannel, and will clean up the connection that way. We are already not
1675 // sending new pointers to the connection when it blocked, but focused events will continue to
1676 // pile up.
1677 ALOGW("Canceling events for %s because it is unresponsive",
1678 connection->inputChannel->getName().c_str());
1679 if (connection->status == Connection::STATUS_NORMAL) {
1680 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1681 "application not responding");
1682 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
1684}
1685
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001686void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001687 if (DEBUG_FOCUS) {
1688 ALOGD("Resetting ANR timeouts.");
1689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
1691 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001692 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001693 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694}
1695
Tiger Huang721e26f2018-07-24 22:26:19 +08001696/**
1697 * Get the display id that the given event should go to. If this event specifies a valid display id,
1698 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1699 * Focused display is the display that the user most recently interacted with.
1700 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001702 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001703 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001704 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001705 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1706 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001707 break;
1708 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001709 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001710 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1711 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 break;
1713 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001714 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001715 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001716 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001717 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001718 case EventEntry::Type::SENSOR:
1719 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001720 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001721 return ADISPLAY_ID_NONE;
1722 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001723 }
1724 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1725}
1726
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001727bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1728 const char* focusedWindowName) {
1729 if (mAnrTracker.empty()) {
1730 // already processed all events that we waited for
1731 mKeyIsWaitingForEventsTimeout = std::nullopt;
1732 return false;
1733 }
1734
1735 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1736 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001737 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001738 mKeyIsWaitingForEventsTimeout = currentTime +
1739 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1740 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741 return true;
1742 }
1743
1744 // We still have pending events, and already started the timer
1745 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1746 return true; // Still waiting
1747 }
1748
1749 // Waited too long, and some connection still hasn't processed all motions
1750 // Just send the key to the focused window
1751 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1752 focusedWindowName);
1753 mKeyIsWaitingForEventsTimeout = std::nullopt;
1754 return false;
1755}
1756
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001757InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1758 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1759 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001760 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
Tiger Huang721e26f2018-07-24 22:26:19 +08001762 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001763 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001764 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001765 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1766
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 // If there is no currently focused window and no focused application
1768 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001769 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1770 ALOGI("Dropping %s event because there is no focused window or focused application in "
1771 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001772 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001773 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 }
1775
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001776 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1777 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1778 // start interacting with another application via touch (app switch). This code can be removed
1779 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1780 // an app is expected to have a focused window.
1781 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1782 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1783 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001784 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1785 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1786 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001788 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001789 ALOGW("Waiting because no window has focus but %s may eventually add a "
1790 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001791 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001792 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001794 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1795 // Already raised ANR. Drop the event
1796 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001797 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001799 } else {
1800 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001801 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001802 }
1803 }
1804
1805 // we have a valid, non-null focused window
1806 resetNoFocusedWindowTimeoutLocked();
1807
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001809 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001810 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 }
1812
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001813 if (focusedWindowHandle->getInfo()->paused) {
1814 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001816 }
1817
1818 // If the event is a key event, then we must wait for all previous events to
1819 // complete before delivering it because previous events may have the
1820 // side-effect of transferring focus to a different window and we want to
1821 // ensure that the following keys are sent to the new window.
1822 //
1823 // Suppose the user touches a button in a window then immediately presses "A".
1824 // If the button causes a pop-up window to appear then we want to ensure that
1825 // the "A" key is delivered to the new pop-up window. This is because users
1826 // often anticipate pending UI changes when typing on a keyboard.
1827 // To obtain this behavior, we must serialize key events with respect to all
1828 // prior input events.
1829 if (entry.type == EventEntry::Type::KEY) {
1830 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1831 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 }
1835
1836 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001837 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001838 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1839 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840
1841 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001842 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843}
1844
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001845/**
1846 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1847 * that are currently unresponsive.
1848 */
1849std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1850 const std::vector<TouchedMonitor>& monitors) const {
1851 std::vector<TouchedMonitor> responsiveMonitors;
1852 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1853 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1854 sp<Connection> connection = getConnectionLocked(
1855 monitor.monitor.inputChannel->getConnectionToken());
1856 if (connection == nullptr) {
1857 ALOGE("Could not find connection for monitor %s",
1858 monitor.monitor.inputChannel->getName().c_str());
1859 return false;
1860 }
1861 if (!connection->responsive) {
1862 ALOGW("Unresponsive monitor %s will not get the new gesture",
1863 connection->inputChannel->getName().c_str());
1864 return false;
1865 }
1866 return true;
1867 });
1868 return responsiveMonitors;
1869}
1870
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001871InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1872 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1873 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001874 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 enum InjectionPermission {
1876 INJECTION_PERMISSION_UNKNOWN,
1877 INJECTION_PERMISSION_GRANTED,
1878 INJECTION_PERMISSION_DENIED
1879 };
1880
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 // For security reasons, we defer updating the touch state until we are sure that
1882 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001883 int32_t displayId = entry.displayId;
1884 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1886
1887 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001890 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1891 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001893 // Copy current touch state into tempTouchState.
1894 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1895 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001896 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001897 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001898 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1899 mTouchStatesByDisplay.find(displayId);
1900 if (oldStateIt != mTouchStatesByDisplay.end()) {
1901 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001902 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001903 }
1904
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001905 bool isSplit = tempTouchState.split;
1906 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1907 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1908 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001909 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1910 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1911 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1912 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1913 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001914 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 bool wrongDevice = false;
1916 if (newGesture) {
1917 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001919 ALOGI("Dropping event because a pointer for a different device is already down "
1920 "in display %" PRId32,
1921 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001922 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001923 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 switchedDevice = false;
1925 wrongDevice = true;
1926 goto Failed;
1927 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001928 tempTouchState.reset();
1929 tempTouchState.down = down;
1930 tempTouchState.deviceId = entry.deviceId;
1931 tempTouchState.source = entry.source;
1932 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001934 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001935 ALOGI("Dropping move event because a pointer for a different device is already active "
1936 "in display %" PRId32,
1937 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001938 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001940 switchedDevice = false;
1941 wrongDevice = true;
1942 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 }
1944
1945 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1946 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1947
Garfield Tan00f511d2019-06-12 16:55:40 -07001948 int32_t x;
1949 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001951 // Always dispatch mouse events to cursor position.
1952 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001953 x = int32_t(entry.xCursorPosition);
1954 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001955 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001956 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1957 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001958 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001960 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1961 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001962
1963 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001964 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00001965 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001968 if (newTouchedWindowHandle != nullptr &&
1969 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001970 // New window supports splitting, but we should never split mouse events.
1971 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 } else if (isSplit) {
1973 // New window does not support splitting but we have already split events.
1974 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001975 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977
1978 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001979 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001981 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001982 }
1983
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1985 ALOGI("Not sending touch event to %s because it is paused",
1986 newTouchedWindowHandle->getName().c_str());
1987 newTouchedWindowHandle = nullptr;
1988 }
1989
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001990 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001991 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001992 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1993 if (!isResponsive) {
1994 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001995 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1996 newTouchedWindowHandle = nullptr;
1997 }
1998 }
1999
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002000 // Drop events that can't be trusted due to occlusion
2001 if (newTouchedWindowHandle != nullptr &&
2002 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2003 TouchOcclusionInfo occlusionInfo =
2004 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002005 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002006 if (DEBUG_TOUCH_OCCLUSION) {
2007 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2008 for (const auto& log : occlusionInfo.debugInfo) {
2009 ALOGD("%s", log.c_str());
2010 }
2011 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002012 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2013 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2014 ALOGW("Dropping untrusted touch event due to %s/%d",
2015 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2016 newTouchedWindowHandle = nullptr;
2017 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002018 }
2019 }
2020
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 // Also don't send the new touch event to unresponsive gesture monitors
2022 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2023
Michael Wright3dd60e22019-03-27 22:06:44 +00002024 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2025 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002026 "(%d, %d) in display %" PRId32 ".",
2027 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002028 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002029 goto Failed;
2030 }
2031
2032 if (newTouchedWindowHandle != nullptr) {
2033 // Set target flags.
2034 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2035 if (isSplit) {
2036 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002038 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2039 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2040 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2041 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2042 }
2043
2044 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002045 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2046 newHoverWindowHandle = nullptr;
2047 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002048 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002049 }
2050
2051 // Update the temporary touch state.
2052 BitSet32 pointerIds;
2053 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002054 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002055 pointerIds.markBit(pointerId);
2056 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002057 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
2059
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002060 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 } else {
2062 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2063
2064 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002066 if (DEBUG_FOCUS) {
2067 ALOGD("Dropping event because the pointer is not down or we previously "
2068 "dropped the pointer down event in display %" PRId32,
2069 displayId);
2070 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002071 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 goto Failed;
2073 }
2074
arthurhung6d4bed92021-03-17 11:59:33 +08002075 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002076
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002079 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2081 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082
2083 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002084 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002085 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002086 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2087 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002088 if (DEBUG_FOCUS) {
2089 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2090 oldTouchedWindowHandle->getName().c_str(),
2091 newTouchedWindowHandle->getName().c_str(), displayId);
2092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002094 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2095 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2096 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097
2098 // Make a slippery entrance into the new window.
2099 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2100 isSplit = true;
2101 }
2102
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002103 int32_t targetFlags =
2104 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 if (isSplit) {
2106 targetFlags |= InputTarget::FLAG_SPLIT;
2107 }
2108 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2109 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002110 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2111 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 }
2113
2114 BitSet32 pointerIds;
2115 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002116 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 }
2120 }
2121 }
2122
2123 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002124 // Let the previous window know that the hover sequence is over, unless we already did it
2125 // when dispatching it as is to newTouchedWindowHandle.
2126 if (mLastHoverWindowHandle != nullptr &&
2127 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2128 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129#if DEBUG_HOVER
2130 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002133 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2134 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 }
2136
Garfield Tandf26e862020-07-01 20:18:19 -07002137 // Let the new window know that the hover sequence is starting, unless we already did it
2138 // when dispatching it as is to newTouchedWindowHandle.
2139 if (newHoverWindowHandle != nullptr &&
2140 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2141 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142#if DEBUG_HOVER
2143 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002144 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002146 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2147 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2148 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150 }
2151
2152 // Check permission to inject into all touched foreground windows and ensure there
2153 // is at least one touched foreground window.
2154 {
2155 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2158 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002160 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 injectionPermission = INJECTION_PERMISSION_DENIED;
2162 goto Failed;
2163 }
2164 }
2165 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002166 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002167 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002168 ALOGI("Dropping event because there is no touched foreground window in display "
2169 "%" PRId32 " or gesture monitor to receive it.",
2170 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002171 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 goto Failed;
2173 }
2174
2175 // Permission granted to injection into all touched foreground windows.
2176 injectionPermission = INJECTION_PERMISSION_GRANTED;
2177 }
2178
2179 // Check whether windows listening for outside touches are owned by the same UID. If it is
2180 // set the policy flag that we will not reveal coordinate information to this window.
2181 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2182 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002183 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002184 if (foregroundWindowHandle) {
2185 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002186 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002187 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2188 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2189 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002190 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2191 InputTarget::FLAG_ZERO_COORDS,
2192 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 }
2195 }
2196 }
2197 }
2198
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 // If this is the first pointer going down and the touched window has a wallpaper
2200 // then also add the touched wallpaper windows so they are locked in for the duration
2201 // of the touch gesture.
2202 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2203 // engine only supports touch events. We would need to add a mechanism similar
2204 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2205 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2206 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002207 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002208 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002209 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002210 getWindowHandlesLocked(displayId);
2211 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002214 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002215 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002216 .addOrUpdateWindow(windowHandle,
2217 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2218 InputTarget::
2219 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2220 InputTarget::FLAG_DISPATCH_AS_IS,
2221 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
2223 }
2224 }
2225 }
2226
2227 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002228 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002230 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002232 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 }
2234
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002235 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002236 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002237 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002238 }
2239
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 // Drop the outside or hover touch windows since we will not care about them
2241 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243
2244Failed:
2245 // Check injection permission once and for all.
2246 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002247 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 injectionPermission = INJECTION_PERMISSION_GRANTED;
2249 } else {
2250 injectionPermission = INJECTION_PERMISSION_DENIED;
2251 }
2252 }
2253
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002254 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2255 return injectionResult;
2256 }
2257
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002259 if (!wrongDevice) {
2260 if (switchedDevice) {
2261 if (DEBUG_FOCUS) {
2262 ALOGD("Conflicting pointer actions: Switched to a different device.");
2263 }
2264 *outConflictingPointerActions = true;
2265 }
2266
2267 if (isHoverAction) {
2268 // Started hovering, therefore no longer down.
2269 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002270 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002271 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2272 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 *outConflictingPointerActions = true;
2275 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002276 tempTouchState.reset();
2277 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2278 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2279 tempTouchState.deviceId = entry.deviceId;
2280 tempTouchState.source = entry.source;
2281 tempTouchState.displayId = displayId;
2282 }
2283 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2284 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2285 // All pointers up or canceled.
2286 tempTouchState.reset();
2287 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2288 // First pointer went down.
2289 if (oldState && oldState->down) {
2290 if (DEBUG_FOCUS) {
2291 ALOGD("Conflicting pointer actions: Down received while already down.");
2292 }
2293 *outConflictingPointerActions = true;
2294 }
2295 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2296 // One pointer went up.
2297 if (isSplit) {
2298 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2299 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002301 for (size_t i = 0; i < tempTouchState.windows.size();) {
2302 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2303 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2304 touchedWindow.pointerIds.clearBit(pointerId);
2305 if (touchedWindow.pointerIds.isEmpty()) {
2306 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2307 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002310 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002312 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002313 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002314
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002315 // Save changes unless the action was scroll in which case the temporary touch
2316 // state was only valid for this one action.
2317 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2318 if (tempTouchState.displayId >= 0) {
2319 mTouchStatesByDisplay[displayId] = tempTouchState;
2320 } else {
2321 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002325 // Update hover state.
2326 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
2328
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 return injectionResult;
2330}
2331
arthurhung6d4bed92021-03-17 11:59:33 +08002332void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2333 const sp<InputWindowHandle> dropWindow =
2334 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002335 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002336 if (dropWindow) {
2337 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2338 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002339 } else {
2340 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002341 }
2342 mDragState.reset();
2343}
2344
2345void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2346 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002347 return;
2348 }
2349
arthurhung6d4bed92021-03-17 11:59:33 +08002350 if (!mDragState->isStartDrag) {
2351 mDragState->isStartDrag = true;
2352 mDragState->isStylusButtonDownAtStart =
2353 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2354 }
2355
arthurhungb89ccb02020-12-30 16:19:01 +08002356 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2357 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2358 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2359 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002360 // Handle the special case : stylus button no longer pressed.
2361 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2362 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2363 finishDragAndDrop(entry.displayId, x, y);
2364 return;
2365 }
2366
arthurhungb89ccb02020-12-30 16:19:01 +08002367 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002368 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002369 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002370 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002371 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2372 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2373 if (mDragState->dragHoverWindowHandle != nullptr) {
2374 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2375 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002376 }
arthurhung6d4bed92021-03-17 11:59:33 +08002377 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002378 }
2379 // enqueue drag location if needed.
2380 if (hoverWindowHandle != nullptr) {
2381 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2382 }
arthurhung6d4bed92021-03-17 11:59:33 +08002383 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2384 finishDragAndDrop(entry.displayId, x, y);
2385 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002386 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002387 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002388 }
2389}
2390
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392 int32_t targetFlags, BitSet32 pointerIds,
2393 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002394 std::vector<InputTarget>::iterator it =
2395 std::find_if(inputTargets.begin(), inputTargets.end(),
2396 [&windowHandle](const InputTarget& inputTarget) {
2397 return inputTarget.inputChannel->getConnectionToken() ==
2398 windowHandle->getToken();
2399 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002400
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002401 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002402
2403 if (it == inputTargets.end()) {
2404 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002405 std::shared_ptr<InputChannel> inputChannel =
2406 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002407 if (inputChannel == nullptr) {
2408 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2409 return;
2410 }
2411 inputTarget.inputChannel = inputChannel;
2412 inputTarget.flags = targetFlags;
2413 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002414 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002415 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002416 inputTargets.push_back(inputTarget);
2417 it = inputTargets.end() - 1;
2418 }
2419
2420 ALOG_ASSERT(it->flags == targetFlags);
2421 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2422
chaviw1ff3d1e2020-07-01 15:53:47 -07002423 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424}
2425
Michael Wright3dd60e22019-03-27 22:06:44 +00002426void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002427 int32_t displayId, float xOffset,
2428 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002429 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2430 mGlobalMonitorsByDisplay.find(displayId);
2431
2432 if (it != mGlobalMonitorsByDisplay.end()) {
2433 const std::vector<Monitor>& monitors = it->second;
2434 for (const Monitor& monitor : monitors) {
2435 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
2438}
2439
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002440void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2441 float yOffset,
2442 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002443 InputTarget target;
2444 target.inputChannel = monitor.inputChannel;
2445 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002446 ui::Transform t;
2447 t.set(xOffset, yOffset);
2448 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002449 inputTargets.push_back(target);
2450}
2451
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002453 const InjectionState* injectionState) {
2454 if (injectionState &&
2455 (windowHandle == nullptr ||
2456 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2457 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002458 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002460 "owned by uid %d",
2461 injectionState->injectorPid, injectionState->injectorUid,
2462 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 } else {
2464 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 }
2467 return false;
2468 }
2469 return true;
2470}
2471
Robert Carrc9bf1d32020-04-13 17:21:08 -07002472/**
2473 * Indicate whether one window handle should be considered as obscuring
2474 * another window handle. We only check a few preconditions. Actually
2475 * checking the bounds is left to the caller.
2476 */
2477static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2478 const sp<InputWindowHandle>& otherHandle) {
2479 // Compare by token so cloned layers aren't counted
2480 if (haveSameToken(windowHandle, otherHandle)) {
2481 return false;
2482 }
2483 auto info = windowHandle->getInfo();
2484 auto otherInfo = otherHandle->getInfo();
2485 if (!otherInfo->visible) {
2486 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002487 } else if (otherInfo->alpha == 0 &&
2488 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2489 // Those act as if they were invisible, so we don't need to flag them.
2490 // We do want to potentially flag touchable windows even if they have 0
2491 // opacity, since they can consume touches and alter the effects of the
2492 // user interaction (eg. apps that rely on
2493 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2494 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2495 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002496 } else if (info->ownerUid == otherInfo->ownerUid) {
2497 // If ownerUid is the same we don't generate occlusion events as there
2498 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002499 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002500 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002501 return false;
2502 } else if (otherInfo->displayId != info->displayId) {
2503 return false;
2504 }
2505 return true;
2506}
2507
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002508/**
2509 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2510 * untrusted, one should check:
2511 *
2512 * 1. If result.hasBlockingOcclusion is true.
2513 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2514 * BLOCK_UNTRUSTED.
2515 *
2516 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2517 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2518 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2519 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2520 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2521 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2522 *
2523 * If neither of those is true, then it means the touch can be allowed.
2524 */
2525InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2526 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002527 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2528 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002529 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2530 TouchOcclusionInfo info;
2531 info.hasBlockingOcclusion = false;
2532 info.obscuringOpacity = 0;
2533 info.obscuringUid = -1;
2534 std::map<int32_t, float> opacityByUid;
2535 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2536 if (windowHandle == otherHandle) {
2537 break; // All future windows are below us. Exit early.
2538 }
2539 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002540 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2541 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002542 if (DEBUG_TOUCH_OCCLUSION) {
2543 info.debugInfo.push_back(
2544 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2545 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002546 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2547 // we perform the checks below to see if the touch can be propagated or not based on the
2548 // window's touch occlusion mode
2549 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2550 info.hasBlockingOcclusion = true;
2551 info.obscuringUid = otherInfo->ownerUid;
2552 info.obscuringPackage = otherInfo->packageName;
2553 break;
2554 }
2555 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2556 uint32_t uid = otherInfo->ownerUid;
2557 float opacity =
2558 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2559 // Given windows A and B:
2560 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2561 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2562 opacityByUid[uid] = opacity;
2563 if (opacity > info.obscuringOpacity) {
2564 info.obscuringOpacity = opacity;
2565 info.obscuringUid = uid;
2566 info.obscuringPackage = otherInfo->packageName;
2567 }
2568 }
2569 }
2570 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002571 if (DEBUG_TOUCH_OCCLUSION) {
2572 info.debugInfo.push_back(
2573 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2574 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002575 return info;
2576}
2577
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002578std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2579 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002580 return StringPrintf(INDENT2
2581 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2582 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2583 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2584 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002585 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002586 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002587 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002588 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2589 info->frameTop, info->frameRight, info->frameBottom,
2590 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002591 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2592 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2593 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002594}
2595
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002596bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2597 if (occlusionInfo.hasBlockingOcclusion) {
2598 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2599 occlusionInfo.obscuringUid);
2600 return false;
2601 }
2602 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2603 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2604 "%.2f, maximum allowed = %.2f)",
2605 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2606 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2607 return false;
2608 }
2609 return true;
2610}
2611
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002612bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2613 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002615 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002616 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002617 if (windowHandle == otherHandle) {
2618 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002621 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002622 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 return true;
2624 }
2625 }
2626 return false;
2627}
2628
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002629bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2630 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002631 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002632 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002633 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002634 if (windowHandle == otherHandle) {
2635 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002636 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002637 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002638 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002639 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002640 return true;
2641 }
2642 }
2643 return false;
2644}
2645
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002646std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002647 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002649 if (applicationHandle != nullptr) {
2650 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002651 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 } else {
2653 return applicationHandle->getName();
2654 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002655 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002656 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002658 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 }
2660}
2661
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002662void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002663 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002664 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2665 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002666 // Focus or pointer capture changed events are passed to apps, but do not represent user
2667 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002668 return;
2669 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002670 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002671 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002672 if (focusedWindowHandle != nullptr) {
2673 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002674 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002676 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677#endif
2678 return;
2679 }
2680 }
2681
2682 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002683 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002684 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002685 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2686 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002687 return;
2688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002690 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002691 eventType = USER_ACTIVITY_EVENT_TOUCH;
2692 }
2693 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002695 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002696 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2697 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002698 return;
2699 }
2700 eventType = USER_ACTIVITY_EVENT_BUTTON;
2701 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002703 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002704 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002705 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002706 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002707 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2708 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002709 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002710 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002711 break;
2712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 }
2714
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002715 std::unique_ptr<CommandEntry> commandEntry =
2716 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002717 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002719 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002720 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721}
2722
2723void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002725 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002726 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002727 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002729 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002730 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002731 ATRACE_NAME(message.c_str());
2732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733#if DEBUG_DISPATCH_CYCLE
2734 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002735 "globalScaleFactor=%f, pointerIds=0x%x %s",
2736 connection->getInputChannelName().c_str(), inputTarget.flags,
2737 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2738 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739#endif
2740
2741 // Skip this event if the connection status is not normal.
2742 // We don't want to enqueue additional outbound events if the connection is broken.
2743 if (connection->status != Connection::STATUS_NORMAL) {
2744#if DEBUG_DISPATCH_CYCLE
2745 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002746 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747#endif
2748 return;
2749 }
2750
2751 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002752 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2753 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2754 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002755 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002757 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002758 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002759 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002760 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 if (!splitMotionEntry) {
2762 return; // split event was dropped
2763 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002764 if (DEBUG_FOCUS) {
2765 ALOGD("channel '%s' ~ Split motion event.",
2766 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002767 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002768 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002769 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2770 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 return;
2772 }
2773 }
2774
2775 // Not splitting. Enqueue dispatch entries for the event as is.
2776 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2777}
2778
2779void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002781 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002782 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002783 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002785 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002786 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002787 ATRACE_NAME(message.c_str());
2788 }
2789
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002790 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791
2792 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002793 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002795 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002796 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002797 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002798 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002799 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002800 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002801 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002802 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002803 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002804 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805
2806 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002807 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 startDispatchCycleLocked(currentTime, connection);
2809 }
2810}
2811
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002813 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002814 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002815 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002816 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2818 connection->getInputChannelName().c_str(),
2819 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002820 ATRACE_NAME(message.c_str());
2821 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002822 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 if (!(inputTargetFlags & dispatchMode)) {
2824 return;
2825 }
2826 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2827
2828 // This is a new event.
2829 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002830 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002831 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002833 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2834 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002835 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002837 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002838 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002839 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002840 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002841 dispatchEntry->resolvedAction = keyEntry.action;
2842 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2845 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2848 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002850 return; // skip the inconsistent event
2851 }
2852 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002855 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002856 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002857 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2858 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2859 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2860 static_cast<int32_t>(IdGenerator::Source::OTHER);
2861 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002862 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2863 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2864 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2865 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2866 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2867 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2868 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2869 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2870 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2871 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2872 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002873 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002874 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 }
2876 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002877 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2878 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002880 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2881 "event",
2882 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002884 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2885 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2891 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2892 }
2893 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2894 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2898 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2901 "event",
2902 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 return; // skip the inconsistent event
2905 }
2906
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002907 dispatchEntry->resolvedEventId =
2908 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2909 ? mIdGenerator.nextId()
2910 : motionEntry.id;
2911 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2912 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2913 ") to MotionEvent(id=0x%" PRIx32 ").",
2914 motionEntry.id, dispatchEntry->resolvedEventId);
2915 ATRACE_NAME(message.c_str());
2916 }
2917
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002918 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2919 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2920 // Skip reporting pointer down outside focus to the policy.
2921 break;
2922 }
2923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002924 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002925 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926
2927 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002929 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002930 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2931 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002932 break;
2933 }
Chris Yef59a2f42020-10-16 12:55:26 -07002934 case EventEntry::Type::SENSOR: {
2935 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2936 break;
2937 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002938 case EventEntry::Type::CONFIGURATION_CHANGED:
2939 case EventEntry::Type::DEVICE_RESET: {
2940 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002941 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002942 break;
2943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 }
2945
2946 // Remember that we are waiting for this dispatch to complete.
2947 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002948 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 }
2950
2951 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002952 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002953 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002954}
2955
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002956/**
2957 * This function is purely for debugging. It helps us understand where the user interaction
2958 * was taking place. For example, if user is touching launcher, we will see a log that user
2959 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2960 * We will see both launcher and wallpaper in that list.
2961 * Once the interaction with a particular set of connections starts, no new logs will be printed
2962 * until the set of interacted connections changes.
2963 *
2964 * The following items are skipped, to reduce the logspam:
2965 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2966 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2967 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2968 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2969 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002970 */
2971void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2972 const std::vector<InputTarget>& targets) {
2973 // Skip ACTION_UP events, and all events other than keys and motions
2974 if (entry.type == EventEntry::Type::KEY) {
2975 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2976 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2977 return;
2978 }
2979 } else if (entry.type == EventEntry::Type::MOTION) {
2980 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2981 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2982 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2983 return;
2984 }
2985 } else {
2986 return; // Not a key or a motion
2987 }
2988
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07002989 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002990 std::vector<sp<Connection>> newConnections;
2991 for (const InputTarget& target : targets) {
2992 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2993 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2994 continue; // Skip windows that receive ACTION_OUTSIDE
2995 }
2996
2997 sp<IBinder> token = target.inputChannel->getConnectionToken();
2998 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002999 if (connection == nullptr) {
3000 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003001 }
3002 newConnectionTokens.insert(std::move(token));
3003 newConnections.emplace_back(connection);
3004 }
3005 if (newConnectionTokens == mInteractionConnectionTokens) {
3006 return; // no change
3007 }
3008 mInteractionConnectionTokens = newConnectionTokens;
3009
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003010 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003011 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003012 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003013 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003014 std::string message = "Interaction with: " + targetList;
3015 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003016 message += "<none>";
3017 }
3018 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3019}
3020
chaviwfd6d3512019-03-25 13:23:49 -07003021void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003022 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003023 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003024 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3025 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003026 return;
3027 }
3028
Vishnu Nairc519ff72021-01-21 08:23:08 -08003029 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003030 if (focusedToken == token) {
3031 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003032 return;
3033 }
3034
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003035 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3036 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003037 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003038 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039}
3040
3041void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003043 if (ATRACE_ENABLED()) {
3044 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003046 ATRACE_NAME(message.c_str());
3047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003049 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050#endif
3051
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003052 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3053 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003055 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003056 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003057 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058
3059 // Publish the event.
3060 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003061 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3062 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003063 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003064 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3065 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003067 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003068 status = connection->inputPublisher
3069 .publishKeyEvent(dispatchEntry->seq,
3070 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3071 keyEntry.source, keyEntry.displayId,
3072 std::move(hmac), dispatchEntry->resolvedAction,
3073 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3074 keyEntry.scanCode, keyEntry.metaState,
3075 keyEntry.repeatCount, keyEntry.downTime,
3076 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 }
3079
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003080 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003081 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003084 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003085
chaviw82357092020-01-28 13:13:06 -08003086 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003087 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3089 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003090 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003091 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3092 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003093 // Don't apply window scale here since we don't want scale to affect raw
3094 // coordinates. The scale will be sent back to the client and applied
3095 // later when requesting relative coordinates.
3096 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3097 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 }
3099 usingCoords = scaledCoords;
3100 }
3101 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 // We don't want the dispatch target to know.
3103 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003104 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003105 scaledCoords[i].clear();
3106 }
3107 usingCoords = scaledCoords;
3108 }
3109 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003110
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003111 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112
3113 // Publish the motion event.
3114 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003115 .publishMotionEvent(dispatchEntry->seq,
3116 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003117 motionEntry.deviceId, motionEntry.source,
3118 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003119 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003120 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003122 motionEntry.edgeFlags, motionEntry.metaState,
3123 motionEntry.buttonState,
3124 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003125 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 motionEntry.xPrecision, motionEntry.yPrecision,
3127 motionEntry.xCursorPosition,
3128 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003129 dispatchEntry->displaySize.x,
3130 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 motionEntry.downTime, motionEntry.eventTime,
3132 motionEntry.pointerCount,
3133 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 break;
3135 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003136
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003137 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003138 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003139 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003140 focusEntry.id,
3141 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003142 mInTouchMode);
3143 break;
3144 }
3145
Prabir Pradhan99987712020-11-10 18:43:05 -08003146 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3147 const auto& captureEntry =
3148 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3149 status = connection->inputPublisher
3150 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3151 captureEntry.pointerCaptureEnabled);
3152 break;
3153 }
3154
arthurhungb89ccb02020-12-30 16:19:01 +08003155 case EventEntry::Type::DRAG: {
3156 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3157 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3158 dragEntry.id, dragEntry.x,
3159 dragEntry.y,
3160 dragEntry.isExiting);
3161 break;
3162 }
3163
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003164 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003165 case EventEntry::Type::DEVICE_RESET:
3166 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003167 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003168 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 }
3172
3173 // Check the result.
3174 if (status) {
3175 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003176 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 "This is unexpected because the wait queue is empty, so the pipe "
3179 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003180 "event to it, status=%s(%d)",
3181 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3182 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3184 } else {
3185 // Pipe is full and we are waiting for the app to finish process some events
3186 // before sending more events to it.
3187#if DEBUG_DISPATCH_CYCLE
3188 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 "waiting for the application to catch up",
3190 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 }
3193 } else {
3194 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003195 "status=%s(%d)",
3196 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3197 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3199 }
3200 return;
3201 }
3202
3203 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003204 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3205 connection->outboundQueue.end(),
3206 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003207 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003208 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003209 if (connection->responsive) {
3210 mAnrTracker.insert(dispatchEntry->timeoutTime,
3211 connection->inputChannel->getConnectionToken());
3212 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003213 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 }
3215}
3216
chaviw09c8d2d2020-08-24 15:48:26 -07003217std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3218 size_t size;
3219 switch (event.type) {
3220 case VerifiedInputEvent::Type::KEY: {
3221 size = sizeof(VerifiedKeyEvent);
3222 break;
3223 }
3224 case VerifiedInputEvent::Type::MOTION: {
3225 size = sizeof(VerifiedMotionEvent);
3226 break;
3227 }
3228 }
3229 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3230 return mHmacKeyManager.sign(start, size);
3231}
3232
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003233const std::array<uint8_t, 32> InputDispatcher::getSignature(
3234 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3235 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3236 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3237 // Only sign events up and down events as the purely move events
3238 // are tied to their up/down counterparts so signing would be redundant.
3239 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3240 verifiedEvent.actionMasked = actionMasked;
3241 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003242 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003243 }
3244 return INVALID_HMAC;
3245}
3246
3247const std::array<uint8_t, 32> InputDispatcher::getSignature(
3248 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3249 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3250 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3251 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003252 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003253}
3254
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003257 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258#if DEBUG_DISPATCH_CYCLE
3259 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003260 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261#endif
3262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003263 if (connection->status == Connection::STATUS_BROKEN ||
3264 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 return;
3266 }
3267
3268 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003269 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270}
3271
3272void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003273 const sp<Connection>& connection,
3274 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275#if DEBUG_DISPATCH_CYCLE
3276 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003277 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278#endif
3279
3280 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003281 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003282 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003283 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003284 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 // The connection appears to be unrecoverably broken.
3287 // Ignore already broken or zombie connections.
3288 if (connection->status == Connection::STATUS_NORMAL) {
3289 connection->status = Connection::STATUS_BROKEN;
3290
3291 if (notify) {
3292 // Notify other system components.
3293 onDispatchCycleBrokenLocked(currentTime, connection);
3294 }
3295 }
3296}
3297
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003298void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3299 while (!queue.empty()) {
3300 DispatchEntry* dispatchEntry = queue.front();
3301 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003302 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 }
3304}
3305
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003306void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
3310 delete dispatchEntry;
3311}
3312
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003313int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3314 std::scoped_lock _l(mLock);
3315 sp<Connection> connection = getConnectionLocked(connectionToken);
3316 if (connection == nullptr) {
3317 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3318 connectionToken.get(), events);
3319 return 0; // remove the callback
3320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003322 bool notify;
3323 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3324 if (!(events & ALOOPER_EVENT_INPUT)) {
3325 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3326 "events=0x%x",
3327 connection->getInputChannelName().c_str(), events);
3328 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 }
3330
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003331 nsecs_t currentTime = now();
3332 bool gotOne = false;
3333 status_t status = OK;
3334 for (;;) {
3335 Result<InputPublisher::ConsumerResponse> result =
3336 connection->inputPublisher.receiveConsumerResponse();
3337 if (!result.ok()) {
3338 status = result.error().code();
3339 break;
3340 }
3341
3342 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3343 const InputPublisher::Finished& finish =
3344 std::get<InputPublisher::Finished>(*result);
3345 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3346 finish.consumeTime);
3347 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003348 if (shouldReportMetricsForConnection(*connection)) {
3349 const InputPublisher::Timeline& timeline =
3350 std::get<InputPublisher::Timeline>(*result);
3351 mLatencyTracker
3352 .trackGraphicsLatency(timeline.inputEventId,
3353 connection->inputChannel->getConnectionToken(),
3354 std::move(timeline.graphicsTimeline));
3355 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003356 }
3357 gotOne = true;
3358 }
3359 if (gotOne) {
3360 runCommandsLockedInterruptible();
3361 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 return 1;
3363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 }
3365
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003366 notify = status != DEAD_OBJECT || !connection->monitor;
3367 if (notify) {
3368 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3369 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3370 status);
3371 }
3372 } else {
3373 // Monitor channels are never explicitly unregistered.
3374 // We do it automatically when the remote endpoint is closed so don't warn about them.
3375 const bool stillHaveWindowHandle =
3376 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3377 notify = !connection->monitor && stillHaveWindowHandle;
3378 if (notify) {
3379 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3380 connection->getInputChannelName().c_str(), events);
3381 }
3382 }
3383
3384 // Remove the channel.
3385 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3386 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387}
3388
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003391 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003392 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 }
3394}
3395
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003397 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003398 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3399 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3400}
3401
3402void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3403 const CancelationOptions& options,
3404 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3405 for (const auto& it : monitorsByDisplay) {
3406 const std::vector<Monitor>& monitors = it.second;
3407 for (const Monitor& monitor : monitors) {
3408 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003409 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003410 }
3411}
3412
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003414 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003415 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003416 if (connection == nullptr) {
3417 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003419
3420 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421}
3422
3423void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3424 const sp<Connection>& connection, const CancelationOptions& options) {
3425 if (connection->status == Connection::STATUS_BROKEN) {
3426 return;
3427 }
3428
3429 nsecs_t currentTime = now();
3430
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003431 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003432 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003434 if (cancelationEvents.empty()) {
3435 return;
3436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003438 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3439 "with reality: %s, mode=%d.",
3440 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3441 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003443
3444 InputTarget target;
3445 sp<InputWindowHandle> windowHandle =
3446 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3447 if (windowHandle != nullptr) {
3448 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003449 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003450 target.globalScaleFactor = windowInfo->globalScaleFactor;
3451 }
3452 target.inputChannel = connection->inputChannel;
3453 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3454
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003455 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003456 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003457 switch (cancelationEventEntry->type) {
3458 case EventEntry::Type::KEY: {
3459 logOutboundKeyDetails("cancel - ",
3460 static_cast<const KeyEntry&>(*cancelationEventEntry));
3461 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003463 case EventEntry::Type::MOTION: {
3464 logOutboundMotionDetails("cancel - ",
3465 static_cast<const MotionEntry&>(*cancelationEventEntry));
3466 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003468 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003469 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3470 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003471 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003472 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003473 break;
3474 }
3475 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003476 case EventEntry::Type::DEVICE_RESET:
3477 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003478 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003479 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003480 break;
3481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 }
3483
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003484 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3485 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003487
3488 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489}
3490
Svet Ganov5d3bc372020-01-26 23:11:07 -08003491void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3492 const sp<Connection>& connection) {
3493 if (connection->status == Connection::STATUS_BROKEN) {
3494 return;
3495 }
3496
3497 nsecs_t currentTime = now();
3498
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003499 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003500 connection->inputState.synthesizePointerDownEvents(currentTime);
3501
3502 if (downEvents.empty()) {
3503 return;
3504 }
3505
3506#if DEBUG_OUTBOUND_EVENT_DETAILS
3507 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3508 connection->getInputChannelName().c_str(), downEvents.size());
3509#endif
3510
3511 InputTarget target;
3512 sp<InputWindowHandle> windowHandle =
3513 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3514 if (windowHandle != nullptr) {
3515 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003516 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003517 target.globalScaleFactor = windowInfo->globalScaleFactor;
3518 }
3519 target.inputChannel = connection->inputChannel;
3520 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3521
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003522 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003523 switch (downEventEntry->type) {
3524 case EventEntry::Type::MOTION: {
3525 logOutboundMotionDetails("down - ",
3526 static_cast<const MotionEntry&>(*downEventEntry));
3527 break;
3528 }
3529
3530 case EventEntry::Type::KEY:
3531 case EventEntry::Type::FOCUS:
3532 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003533 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003534 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003535 case EventEntry::Type::SENSOR:
3536 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003537 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003538 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003539 break;
3540 }
3541 }
3542
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003543 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3544 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003545 }
3546
3547 startDispatchCycleLocked(currentTime, connection);
3548}
3549
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003550std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3551 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 ALOG_ASSERT(pointerIds.value != 0);
3553
3554 uint32_t splitPointerIndexMap[MAX_POINTERS];
3555 PointerProperties splitPointerProperties[MAX_POINTERS];
3556 PointerCoords splitPointerCoords[MAX_POINTERS];
3557
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003558 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 uint32_t splitPointerCount = 0;
3560
3561 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003562 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003564 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 uint32_t pointerId = uint32_t(pointerProperties.id);
3566 if (pointerIds.hasBit(pointerId)) {
3567 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3568 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3569 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003570 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 splitPointerCount += 1;
3572 }
3573 }
3574
3575 if (splitPointerCount != pointerIds.count()) {
3576 // This is bad. We are missing some of the pointers that we expected to deliver.
3577 // Most likely this indicates that we received an ACTION_MOVE events that has
3578 // different pointer ids than we expected based on the previous ACTION_DOWN
3579 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3580 // in this way.
3581 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 "we expected there to be %d pointers. This probably means we received "
3583 "a broken sequence of pointer ids from the input device.",
3584 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003585 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 }
3587
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003588 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003590 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3591 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3593 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003594 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 uint32_t pointerId = uint32_t(pointerProperties.id);
3596 if (pointerIds.hasBit(pointerId)) {
3597 if (pointerIds.count() == 1) {
3598 // The first/last pointer went down/up.
3599 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003601 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3602 ? AMOTION_EVENT_ACTION_CANCEL
3603 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 } else {
3605 // A secondary pointer went down/up.
3606 uint32_t splitPointerIndex = 0;
3607 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3608 splitPointerIndex += 1;
3609 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003610 action = maskedAction |
3611 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
3613 } else {
3614 // An unrelated pointer changed.
3615 action = AMOTION_EVENT_ACTION_MOVE;
3616 }
3617 }
3618
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003619 int32_t newId = mIdGenerator.nextId();
3620 if (ATRACE_ENABLED()) {
3621 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3622 ") to MotionEvent(id=0x%" PRIx32 ").",
3623 originalMotionEntry.id, newId);
3624 ATRACE_NAME(message.c_str());
3625 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003626 std::unique_ptr<MotionEntry> splitMotionEntry =
3627 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3628 originalMotionEntry.deviceId, originalMotionEntry.source,
3629 originalMotionEntry.displayId,
3630 originalMotionEntry.policyFlags, action,
3631 originalMotionEntry.actionButton,
3632 originalMotionEntry.flags, originalMotionEntry.metaState,
3633 originalMotionEntry.buttonState,
3634 originalMotionEntry.classification,
3635 originalMotionEntry.edgeFlags,
3636 originalMotionEntry.xPrecision,
3637 originalMotionEntry.yPrecision,
3638 originalMotionEntry.xCursorPosition,
3639 originalMotionEntry.yCursorPosition,
3640 originalMotionEntry.downTime, splitPointerCount,
3641 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003643 if (originalMotionEntry.injectionState) {
3644 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 splitMotionEntry->injectionState->refCount += 1;
3646 }
3647
3648 return splitMotionEntry;
3649}
3650
3651void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3652#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003653 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654#endif
3655
3656 bool needWake;
3657 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003658 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003660 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3661 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3662 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 } // release lock
3664
3665 if (needWake) {
3666 mLooper->wake();
3667 }
3668}
3669
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003670/**
3671 * If one of the meta shortcuts is detected, process them here:
3672 * Meta + Backspace -> generate BACK
3673 * Meta + Enter -> generate HOME
3674 * This will potentially overwrite keyCode and metaState.
3675 */
3676void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003678 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3679 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3680 if (keyCode == AKEYCODE_DEL) {
3681 newKeyCode = AKEYCODE_BACK;
3682 } else if (keyCode == AKEYCODE_ENTER) {
3683 newKeyCode = AKEYCODE_HOME;
3684 }
3685 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003686 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003687 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003688 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003689 keyCode = newKeyCode;
3690 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3691 }
3692 } else if (action == AKEY_EVENT_ACTION_UP) {
3693 // In order to maintain a consistent stream of up and down events, check to see if the key
3694 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3695 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003696 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003697 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003698 auto replacementIt = mReplacedKeys.find(replacement);
3699 if (replacementIt != mReplacedKeys.end()) {
3700 keyCode = replacementIt->second;
3701 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003702 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3703 }
3704 }
3705}
3706
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3708#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003709 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3710 "policyFlags=0x%x, action=0x%x, "
3711 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3712 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3713 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3714 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715#endif
3716 if (!validateKeyEvent(args->action)) {
3717 return;
3718 }
3719
3720 uint32_t policyFlags = args->policyFlags;
3721 int32_t flags = args->flags;
3722 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003723 // InputDispatcher tracks and generates key repeats on behalf of
3724 // whatever notifies it, so repeatCount should always be set to 0
3725 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3727 policyFlags |= POLICY_FLAG_VIRTUAL;
3728 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 if (policyFlags & POLICY_FLAG_FUNCTION) {
3731 metaState |= AMETA_FUNCTION_ON;
3732 }
3733
3734 policyFlags |= POLICY_FLAG_TRUSTED;
3735
Michael Wright78f24442014-08-06 15:55:28 -07003736 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003737 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003738
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003740 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003741 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3742 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743
Michael Wright2b3c3302018-03-02 17:19:13 +00003744 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003746 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3747 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003748 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 bool needWake;
3752 { // acquire lock
3753 mLock.lock();
3754
3755 if (shouldSendKeyToInputFilterLocked(args)) {
3756 mLock.unlock();
3757
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003758 policyFlags |= POLICY_FLAG_FILTERED | POLICY_FLAG_INPUTFILTER_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3760 return; // event was consumed by the filter
3761 }
3762
3763 mLock.lock();
3764 }
3765
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003766 std::unique_ptr<KeyEntry> newEntry =
3767 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3768 args->displayId, policyFlags, args->action, flags,
3769 keyCode, args->scanCode, metaState, repeatCount,
3770 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003772 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 mLock.unlock();
3774 } // release lock
3775
3776 if (needWake) {
3777 mLooper->wake();
3778 }
3779}
3780
3781bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3782 return mInputFilterEnabled;
3783}
3784
3785void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3786#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003787 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3788 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003789 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3790 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003791 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003792 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3793 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3794 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3795 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 for (uint32_t i = 0; i < args->pointerCount; i++) {
3797 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003798 "x=%f, y=%f, pressure=%f, size=%f, "
3799 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3800 "orientation=%f",
3801 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3802 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3803 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3804 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3805 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3806 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3807 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3808 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3809 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3810 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3814 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 return;
3816 }
3817
3818 uint32_t policyFlags = args->policyFlags;
3819 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003820
3821 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003822 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003823 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3824 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827
3828 bool needWake;
3829 { // acquire lock
3830 mLock.lock();
3831
3832 if (shouldSendMotionToInputFilterLocked(args)) {
3833 mLock.unlock();
3834
3835 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003836 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003837 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3838 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003839 args->metaState, args->buttonState, args->classification, transform,
3840 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003841 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3842 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003843 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844
3845 policyFlags |= POLICY_FLAG_FILTERED;
3846 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3847 return; // event was consumed by the filter
3848 }
3849
3850 mLock.lock();
3851 }
3852
3853 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003854 std::unique_ptr<MotionEntry> newEntry =
3855 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3856 args->source, args->displayId, policyFlags,
3857 args->action, args->actionButton, args->flags,
3858 args->metaState, args->buttonState,
3859 args->classification, args->edgeFlags,
3860 args->xPrecision, args->yPrecision,
3861 args->xCursorPosition, args->yCursorPosition,
3862 args->downTime, args->pointerCount,
3863 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003865 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866 mLock.unlock();
3867 } // release lock
3868
3869 if (needWake) {
3870 mLooper->wake();
3871 }
3872}
3873
Chris Yef59a2f42020-10-16 12:55:26 -07003874void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3875#if DEBUG_INBOUND_EVENT_DETAILS
3876 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3877 " sensorType=%s",
3878 args->id, args->eventTime, args->deviceId, args->source,
3879 NamedEnum::string(args->sensorType).c_str());
3880#endif
3881
3882 bool needWake;
3883 { // acquire lock
3884 mLock.lock();
3885
3886 // Just enqueue a new sensor event.
3887 std::unique_ptr<SensorEntry> newEntry =
3888 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3889 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3890 args->sensorType, args->accuracy,
3891 args->accuracyChanged, args->values);
3892
3893 needWake = enqueueInboundEventLocked(std::move(newEntry));
3894 mLock.unlock();
3895 } // release lock
3896
3897 if (needWake) {
3898 mLooper->wake();
3899 }
3900}
3901
Chris Yefb552902021-02-03 17:18:37 -08003902void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3903#if DEBUG_INBOUND_EVENT_DETAILS
3904 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3905 args->deviceId, args->isOn);
3906#endif
3907 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3908}
3909
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003911 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912}
3913
3914void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3915#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003916 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003917 "switchMask=0x%08x",
3918 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919#endif
3920
3921 uint32_t policyFlags = args->policyFlags;
3922 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003923 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924}
3925
3926void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3927#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003928 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3929 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930#endif
3931
3932 bool needWake;
3933 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003934 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003936 std::unique_ptr<DeviceResetEntry> newEntry =
3937 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3938 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 } // release lock
3940
3941 if (needWake) {
3942 mLooper->wake();
3943 }
3944}
3945
Prabir Pradhan7e186182020-11-10 13:56:45 -08003946void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3947#if DEBUG_INBOUND_EVENT_DETAILS
3948 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3949 args->enabled ? "true" : "false");
3950#endif
3951
Prabir Pradhan99987712020-11-10 18:43:05 -08003952 bool needWake;
3953 { // acquire lock
3954 std::scoped_lock _l(mLock);
3955 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3956 args->enabled);
3957 needWake = enqueueInboundEventLocked(std::move(entry));
3958 } // release lock
3959
3960 if (needWake) {
3961 mLooper->wake();
3962 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003963}
3964
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003965InputEventInjectionResult InputDispatcher::injectInputEvent(
3966 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3967 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968#if DEBUG_INBOUND_EVENT_DETAILS
3969 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003970 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3971 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003973 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
3975 policyFlags |= POLICY_FLAG_INJECTED;
3976 if (hasInjectionPermission(injectorPid, injectorUid)) {
3977 policyFlags |= POLICY_FLAG_TRUSTED;
3978 }
3979
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003980 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
3981 // that have gone through the InputFilter. If the event passed through the InputFilter,
3982 // but did not get modified, assign the provided device id. If the InputFilter modifies the
3983 // events in any way, it is responsible for removing this flag.
3984 // If the injected event originated from accessibility, assign the accessibility device id,
3985 // so that it can be distinguished from regular injected events.
3986 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
3987 if (policyFlags & POLICY_FLAG_INPUTFILTER_TRUSTED) {
3988 resolvedDeviceId = event->getDeviceId();
3989 } else if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
3990 resolvedDeviceId = ACCESSIBILITY_DEVICE_ID;
3991 }
3992
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003993 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003995 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003996 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3997 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003998 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003999 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004002 int32_t flags = incomingKey.getFlags();
4003 int32_t keyCode = incomingKey.getKeyCode();
4004 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004005 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004006 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004007 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004008 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004009 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4010 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4011 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004013 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4014 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004015 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004016
4017 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4018 android::base::Timer t;
4019 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4020 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4021 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4022 std::to_string(t.duration().count()).c_str());
4023 }
4024 }
4025
4026 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004027 std::unique_ptr<KeyEntry> injectedEntry =
4028 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004029 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004030 incomingKey.getDisplayId(), policyFlags, action,
4031 flags, keyCode, incomingKey.getScanCode(), metaState,
4032 incomingKey.getRepeatCount(),
4033 incomingKey.getDownTime());
4034 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004035 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 }
4037
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004039 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4040 int32_t action = motionEvent.getAction();
4041 size_t pointerCount = motionEvent.getPointerCount();
4042 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4043 int32_t actionButton = motionEvent.getActionButton();
4044 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004045 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004046 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 }
4048
4049 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004050 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004051 android::base::Timer t;
4052 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4053 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4054 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4055 std::to_string(t.duration().count()).c_str());
4056 }
4057 }
4058
4059 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004060 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4061 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004062 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004063 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4064 resolvedDeviceId, motionEvent.getSource(),
4065 motionEvent.getDisplayId(), policyFlags, action,
4066 actionButton, motionEvent.getFlags(),
4067 motionEvent.getMetaState(),
4068 motionEvent.getButtonState(),
4069 motionEvent.getClassification(),
4070 motionEvent.getEdgeFlags(),
4071 motionEvent.getXPrecision(),
4072 motionEvent.getYPrecision(),
4073 motionEvent.getRawXCursorPosition(),
4074 motionEvent.getRawYCursorPosition(),
4075 motionEvent.getDownTime(), uint32_t(pointerCount),
4076 pointerProperties, samplePointerCoords,
4077 motionEvent.getXOffset(),
4078 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004080 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 sampleEventTimes += 1;
4082 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004083 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004084 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4085 resolvedDeviceId, motionEvent.getSource(),
4086 motionEvent.getDisplayId(), policyFlags,
4087 action, actionButton, motionEvent.getFlags(),
4088 motionEvent.getMetaState(),
4089 motionEvent.getButtonState(),
4090 motionEvent.getClassification(),
4091 motionEvent.getEdgeFlags(),
4092 motionEvent.getXPrecision(),
4093 motionEvent.getYPrecision(),
4094 motionEvent.getRawXCursorPosition(),
4095 motionEvent.getRawYCursorPosition(),
4096 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004097 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004098 samplePointerCoords, motionEvent.getXOffset(),
4099 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004100 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004101 }
4102 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004105 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004106 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004107 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 }
4109
4110 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004111 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 injectionState->injectionIsAsync = true;
4113 }
4114
4115 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004116 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
4118 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004119 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004120 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004121 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 }
4123
4124 mLock.unlock();
4125
4126 if (needWake) {
4127 mLooper->wake();
4128 }
4129
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004130 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004132 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004134 if (syncMode == InputEventInjectionSync::NONE) {
4135 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 } else {
4137 for (;;) {
4138 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004139 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 break;
4141 }
4142
4143 nsecs_t remainingTimeout = endTime - now();
4144 if (remainingTimeout <= 0) {
4145#if DEBUG_INJECTION
4146 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004147 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004149 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 break;
4151 }
4152
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004153 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 }
4155
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004156 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4157 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 while (injectionState->pendingForegroundDispatches != 0) {
4159#if DEBUG_INJECTION
4160 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162#endif
4163 nsecs_t remainingTimeout = endTime - now();
4164 if (remainingTimeout <= 0) {
4165#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004166 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4167 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004169 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 break;
4171 }
4172
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004173 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175 }
4176 }
4177
4178 injectionState->release();
4179 } // release lock
4180
4181#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004182 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184#endif
4185
4186 return injectionResult;
4187}
4188
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004189std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004190 std::array<uint8_t, 32> calculatedHmac;
4191 std::unique_ptr<VerifiedInputEvent> result;
4192 switch (event.getType()) {
4193 case AINPUT_EVENT_TYPE_KEY: {
4194 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4195 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4196 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004197 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004198 break;
4199 }
4200 case AINPUT_EVENT_TYPE_MOTION: {
4201 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4202 VerifiedMotionEvent verifiedMotionEvent =
4203 verifiedMotionEventFromMotionEvent(motionEvent);
4204 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004205 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004206 break;
4207 }
4208 default: {
4209 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4210 return nullptr;
4211 }
4212 }
4213 if (calculatedHmac == INVALID_HMAC) {
4214 return nullptr;
4215 }
4216 if (calculatedHmac != event.getHmac()) {
4217 return nullptr;
4218 }
4219 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004220}
4221
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 return injectorUid == 0 ||
4224 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225}
4226
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004227void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004228 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004229 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 if (injectionState) {
4231#if DEBUG_INJECTION
4232 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 "injectorPid=%d, injectorUid=%d",
4234 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235#endif
4236
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004237 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 // Log the outcome since the injector did not wait for the injection result.
4239 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004240 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 ALOGV("Asynchronous input event injection succeeded.");
4242 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 ALOGW("Asynchronous input event injection failed.");
4245 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004246 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 ALOGW("Asynchronous input event injection permission denied.");
4248 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004249 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 ALOGW("Asynchronous input event injection timed out.");
4251 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004252 case InputEventInjectionResult::PENDING:
4253 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4254 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 }
4256 }
4257
4258 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004259 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
4261}
4262
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4264 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 if (injectionState) {
4266 injectionState->pendingForegroundDispatches += 1;
4267 }
4268}
4269
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004270void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4271 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 if (injectionState) {
4273 injectionState->pendingForegroundDispatches -= 1;
4274
4275 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004276 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278 }
4279}
4280
Vishnu Nairad321cd2020-08-20 16:40:21 -07004281const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004282 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004283 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4284 auto it = mWindowHandlesByDisplay.find(displayId);
4285 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004286}
4287
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004289 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004290 if (windowHandleToken == nullptr) {
4291 return nullptr;
4292 }
4293
Arthur Hungb92218b2018-08-14 12:00:21 +08004294 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004295 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004296 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004297 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004298 return windowHandle;
4299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004302 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303}
4304
Vishnu Nairad321cd2020-08-20 16:40:21 -07004305sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4306 int displayId) const {
4307 if (windowHandleToken == nullptr) {
4308 return nullptr;
4309 }
4310
4311 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4312 if (windowHandle->getToken() == windowHandleToken) {
4313 return windowHandle;
4314 }
4315 }
4316 return nullptr;
4317}
4318
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004319sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4320 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004321 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004322 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004323 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004324 if (handle->getId() == windowHandle->getId() &&
4325 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004326 if (windowHandle->getInfo()->displayId != it.first) {
4327 ALOGE("Found window %s in display %" PRId32
4328 ", but it should belong to display %" PRId32,
4329 windowHandle->getName().c_str(), it.first,
4330 windowHandle->getInfo()->displayId);
4331 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004332 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
4335 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004336 return nullptr;
4337}
4338
4339sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4340 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4341 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342}
4343
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004344bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4345 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4346 const bool noInputChannel =
4347 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4348 if (connection != nullptr && noInputChannel) {
4349 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4350 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4351 return false;
4352 }
4353
4354 if (connection == nullptr) {
4355 if (!noInputChannel) {
4356 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4357 }
4358 return false;
4359 }
4360 if (!connection->responsive) {
4361 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4362 return false;
4363 }
4364 return true;
4365}
4366
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004367std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4368 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004369 auto connectionIt = mConnectionsByToken.find(token);
4370 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004371 return nullptr;
4372 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004373 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004374}
4375
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004376void InputDispatcher::updateWindowHandlesForDisplayLocked(
4377 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4378 if (inputWindowHandles.empty()) {
4379 // Remove all handles on a display if there are no windows left.
4380 mWindowHandlesByDisplay.erase(displayId);
4381 return;
4382 }
4383
4384 // Since we compare the pointer of input window handles across window updates, we need
4385 // to make sure the handle object for the same window stays unchanged across updates.
4386 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004387 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004388 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004389 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004390 }
4391
4392 std::vector<sp<InputWindowHandle>> newHandles;
4393 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4394 if (!handle->updateInfo()) {
4395 // handle no longer valid
4396 continue;
4397 }
4398
4399 const InputWindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004400 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004401 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004402 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4403 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4404 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004405 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004406 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004407 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004408 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004409 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004410 }
4411
4412 if (info->displayId != displayId) {
4413 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4414 handle->getName().c_str(), displayId, info->displayId);
4415 continue;
4416 }
4417
Robert Carredd13602020-04-13 17:24:34 -07004418 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4419 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004420 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004421 oldHandle->updateFrom(handle);
4422 newHandles.push_back(oldHandle);
4423 } else {
4424 newHandles.push_back(handle);
4425 }
4426 }
4427
4428 // Insert or replace
4429 mWindowHandlesByDisplay[displayId] = newHandles;
4430}
4431
Arthur Hung72d8dc32020-03-28 00:48:39 +00004432void InputDispatcher::setInputWindows(
4433 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4434 { // acquire lock
4435 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004436 for (const auto& [displayId, handles] : handlesPerDisplay) {
4437 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004438 }
4439 }
4440 // Wake up poll loop since it may need to make new input dispatching choices.
4441 mLooper->wake();
4442}
4443
Arthur Hungb92218b2018-08-14 12:00:21 +08004444/**
4445 * Called from InputManagerService, update window handle list by displayId that can receive input.
4446 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4447 * If set an empty list, remove all handles from the specific display.
4448 * For focused handle, check if need to change and send a cancel event to previous one.
4449 * For removed handle, check if need to send a cancel event if already in touch.
4450 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004451void InputDispatcher::setInputWindowsLocked(
4452 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004453 if (DEBUG_FOCUS) {
4454 std::string windowList;
4455 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4456 windowList += iwh->getName() + " ";
4457 }
4458 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004461 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4462 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4463 const bool noInputWindow =
4464 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4465 if (noInputWindow && window->getToken() != nullptr) {
4466 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4467 window->getName().c_str());
4468 window->releaseChannel();
4469 }
4470 }
4471
Arthur Hung72d8dc32020-03-28 00:48:39 +00004472 // Copy old handles for release if they are no longer present.
4473 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004475 // Save the old windows' orientation by ID before it gets updated.
4476 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4477 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4478 oldWindowOrientations.emplace(handle->getId(),
4479 handle->getInfo()->transform.getOrientation());
4480 }
4481
Arthur Hung72d8dc32020-03-28 00:48:39 +00004482 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004483
Vishnu Nair958da932020-08-21 17:12:37 -07004484 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4485 if (mLastHoverWindowHandle &&
4486 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4487 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004488 mLastHoverWindowHandle = nullptr;
4489 }
4490
Vishnu Nairc519ff72021-01-21 08:23:08 -08004491 std::optional<FocusResolver::FocusChanges> changes =
4492 mFocusResolver.setInputWindows(displayId, windowHandles);
4493 if (changes) {
4494 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004497 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4498 mTouchStatesByDisplay.find(displayId);
4499 if (stateIt != mTouchStatesByDisplay.end()) {
4500 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004501 for (size_t i = 0; i < state.windows.size();) {
4502 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004503 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004504 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004505 ALOGD("Touched window was removed: %s in display %" PRId32,
4506 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004507 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004508 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004509 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4510 if (touchedInputChannel != nullptr) {
4511 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4512 "touched window was removed");
4513 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004515 state.windows.erase(state.windows.begin() + i);
4516 } else {
4517 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
4519 }
arthurhungb89ccb02020-12-30 16:19:01 +08004520
arthurhung6d4bed92021-03-17 11:59:33 +08004521 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004522 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004523 if (mDragState &&
4524 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004525 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004526 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004527 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004528 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004529
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004530 if (isPerWindowInputRotationEnabled()) {
4531 // Determine if the orientation of any of the input windows have changed, and cancel all
4532 // pointer events if necessary.
4533 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4534 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4535 if (newWindowHandle != nullptr &&
4536 newWindowHandle->getInfo()->transform.getOrientation() !=
4537 oldWindowOrientations[oldWindowHandle->getId()]) {
4538 std::shared_ptr<InputChannel> inputChannel =
4539 getInputChannelLocked(newWindowHandle->getToken());
4540 if (inputChannel != nullptr) {
4541 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4542 "touched window's orientation changed");
4543 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4544 }
4545 }
4546 }
4547 }
4548
Arthur Hung72d8dc32020-03-28 00:48:39 +00004549 // Release information for windows that are no longer present.
4550 // This ensures that unused input channels are released promptly.
4551 // Otherwise, they might stick around until the window handle is destroyed
4552 // which might not happen until the next GC.
4553 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004554 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004555 if (DEBUG_FOCUS) {
4556 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004557 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004558 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004559 // To avoid making too many calls into the compat framework, only
4560 // check for window flags when windows are going away.
4561 // TODO(b/157929241) : delete this. This is only needed temporarily
4562 // in order to gather some data about the flag usage
4563 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4564 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4565 oldWindowHandle->getName().c_str());
4566 if (mCompatService != nullptr) {
4567 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4568 oldWindowHandle->getInfo()->ownerUid);
4569 }
4570 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004571 }
chaviw291d88a2019-02-14 10:33:58 -08004572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573}
4574
4575void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004576 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004577 if (DEBUG_FOCUS) {
4578 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4579 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4580 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004581 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004582 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004583 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 } // release lock
4585
4586 // Wake up poll loop since it may need to make new input dispatching choices.
4587 mLooper->wake();
4588}
4589
Vishnu Nair599f1412021-06-21 10:39:58 -07004590void InputDispatcher::setFocusedApplicationLocked(
4591 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4592 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4593 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4594
4595 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4596 return; // This application is already focused. No need to wake up or change anything.
4597 }
4598
4599 // Set the new application handle.
4600 if (inputApplicationHandle != nullptr) {
4601 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4602 } else {
4603 mFocusedApplicationHandlesByDisplay.erase(displayId);
4604 }
4605
4606 // No matter what the old focused application was, stop waiting on it because it is
4607 // no longer focused.
4608 resetNoFocusedWindowTimeoutLocked();
4609}
4610
Tiger Huang721e26f2018-07-24 22:26:19 +08004611/**
4612 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4613 * the display not specified.
4614 *
4615 * We track any unreleased events for each window. If a window loses the ability to receive the
4616 * released event, we will send a cancel event to it. So when the focused display is changed, we
4617 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4618 * display. The display-specified events won't be affected.
4619 */
4620void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004621 if (DEBUG_FOCUS) {
4622 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4623 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004624 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004625 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004626
4627 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004628 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004629 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004630 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004631 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004632 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004633 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004634 CancelationOptions
4635 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4636 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004637 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004638 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4639 }
4640 }
4641 mFocusedDisplayId = displayId;
4642
Chris Ye3c2d6f52020-08-09 10:39:48 -07004643 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004644 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004645 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004646
Vishnu Nairad321cd2020-08-20 16:40:21 -07004647 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004648 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004649 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004650 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004651 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004652 }
4653 }
4654 }
4655
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004656 if (DEBUG_FOCUS) {
4657 logDispatchStateLocked();
4658 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004659 } // release lock
4660
4661 // Wake up poll loop since it may need to make new input dispatching choices.
4662 mLooper->wake();
4663}
4664
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004666 if (DEBUG_FOCUS) {
4667 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669
4670 bool changed;
4671 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004672 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673
4674 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4675 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004676 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 }
4678
4679 if (mDispatchEnabled && !enabled) {
4680 resetAndDropEverythingLocked("dispatcher is being disabled");
4681 }
4682
4683 mDispatchEnabled = enabled;
4684 mDispatchFrozen = frozen;
4685 changed = true;
4686 } else {
4687 changed = false;
4688 }
4689
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004690 if (DEBUG_FOCUS) {
4691 logDispatchStateLocked();
4692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 } // release lock
4694
4695 if (changed) {
4696 // Wake up poll loop since it may need to make new input dispatching choices.
4697 mLooper->wake();
4698 }
4699}
4700
4701void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004702 if (DEBUG_FOCUS) {
4703 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705
4706 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004707 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708
4709 if (mInputFilterEnabled == enabled) {
4710 return;
4711 }
4712
4713 mInputFilterEnabled = enabled;
4714 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4715 } // release lock
4716
4717 // Wake up poll loop since there might be work to do to drop everything.
4718 mLooper->wake();
4719}
4720
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004721void InputDispatcher::setInTouchMode(bool inTouchMode) {
4722 std::scoped_lock lock(mLock);
4723 mInTouchMode = inTouchMode;
4724}
4725
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004726void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4727 if (opacity < 0 || opacity > 1) {
4728 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4729 return;
4730 }
4731
4732 std::scoped_lock lock(mLock);
4733 mMaximumObscuringOpacityForTouch = opacity;
4734}
4735
4736void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4737 std::scoped_lock lock(mLock);
4738 mBlockUntrustedTouchesMode = mode;
4739}
4740
arthurhungb89ccb02020-12-30 16:19:01 +08004741bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4742 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004743 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004744 if (DEBUG_FOCUS) {
4745 ALOGD("Trivial transfer to same window.");
4746 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004747 return true;
4748 }
4749
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004751 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
chaviwfbe5d9c2018-12-26 12:23:37 -08004753 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4754 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004755 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004756 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 return false;
4758 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004759 if (DEBUG_FOCUS) {
4760 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4761 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004764 if (DEBUG_FOCUS) {
4765 ALOGD("Cannot transfer focus because windows are on different displays.");
4766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 return false;
4768 }
4769
4770 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004771 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4772 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004773 for (size_t i = 0; i < state.windows.size(); i++) {
4774 const TouchedWindow& touchedWindow = state.windows[i];
4775 if (touchedWindow.windowHandle == fromWindowHandle) {
4776 int32_t oldTargetFlags = touchedWindow.targetFlags;
4777 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004779 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781 int32_t newTargetFlags = oldTargetFlags &
4782 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4783 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004784 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785
arthurhungb89ccb02020-12-30 16:19:01 +08004786 // Store the dragging window.
4787 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004788 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004789 }
4790
Jeff Brownf086ddb2014-02-11 14:28:48 -08004791 found = true;
4792 goto Found;
4793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 }
4795 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004796 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004799 if (DEBUG_FOCUS) {
4800 ALOGD("Focus transfer failed because from window did not have focus.");
4801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 return false;
4803 }
4804
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004805 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4806 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004807 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004808 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809 CancelationOptions
4810 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4811 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004813 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 }
4815
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004816 if (DEBUG_FOCUS) {
4817 logDispatchStateLocked();
4818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 } // release lock
4820
4821 // Wake up poll loop since it may need to make new input dispatching choices.
4822 mLooper->wake();
4823 return true;
4824}
4825
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004826// Binder call
4827bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4828 sp<IBinder> fromToken;
4829 { // acquire lock
4830 std::scoped_lock _l(mLock);
4831
4832 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4833 if (toWindowHandle == nullptr) {
4834 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4835 return false;
4836 }
4837
4838 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4839
4840 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4841 if (touchStateIt == mTouchStatesByDisplay.end()) {
4842 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4843 displayId);
4844 return false;
4845 }
4846
4847 TouchState& state = touchStateIt->second;
4848 if (state.windows.size() != 1) {
4849 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4850 state.windows.size());
4851 return false;
4852 }
4853 const TouchedWindow& touchedWindow = state.windows[0];
4854 fromToken = touchedWindow.windowHandle->getToken();
4855 } // release lock
4856
4857 return transferTouchFocus(fromToken, destChannelToken);
4858}
4859
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004861 if (DEBUG_FOCUS) {
4862 ALOGD("Resetting and dropping all events (%s).", reason);
4863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864
4865 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4866 synthesizeCancelationEventsForAllConnectionsLocked(options);
4867
4868 resetKeyRepeatLocked();
4869 releasePendingEventLocked();
4870 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004871 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004874 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004876 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877}
4878
4879void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004880 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 dumpDispatchStateLocked(dump);
4882
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004883 std::istringstream stream(dump);
4884 std::string line;
4885
4886 while (std::getline(stream, line, '\n')) {
4887 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 }
4889}
4890
Prabir Pradhan99987712020-11-10 18:43:05 -08004891std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4892 std::string dump;
4893
4894 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4895 toString(mFocusedWindowRequestedPointerCapture));
4896
4897 std::string windowName = "None";
4898 if (mWindowTokenWithPointerCapture) {
4899 const sp<InputWindowHandle> captureWindowHandle =
4900 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4901 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4902 : "token has capture without window";
4903 }
4904 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4905
4906 return dump;
4907}
4908
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004909void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004910 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4911 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4912 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004913 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
Tiger Huang721e26f2018-07-24 22:26:19 +08004915 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4916 dump += StringPrintf(INDENT "FocusedApplications:\n");
4917 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4918 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004919 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004920 const std::chrono::duration timeout =
4921 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004922 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004923 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004924 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004927 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004929
Vishnu Nairc519ff72021-01-21 08:23:08 -08004930 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004931 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004933 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004934 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004935 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4936 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004937 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004938 state.displayId, toString(state.down), toString(state.split),
4939 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004940 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004941 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004942 for (size_t i = 0; i < state.windows.size(); i++) {
4943 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004944 dump += StringPrintf(INDENT4
4945 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4946 i, touchedWindow.windowHandle->getName().c_str(),
4947 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004948 }
4949 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004950 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 }
4953 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004954 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 }
4956
arthurhung6d4bed92021-03-17 11:59:33 +08004957 if (mDragState) {
4958 dump += StringPrintf(INDENT "DragState:\n");
4959 mDragState->dump(dump, INDENT2);
4960 }
4961
Arthur Hungb92218b2018-08-14 12:00:21 +08004962 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004963 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004964 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004965 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004966 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004967 dump += INDENT2 "Windows:\n";
4968 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004969 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004970 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004972 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004973 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004974 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004975 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004976 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004977 "applicationInfo.name=%s, "
4978 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004979 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004980 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004981 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004982 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004983 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004984 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004985 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004986 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004987 windowInfo->frameLeft, windowInfo->frameTop,
4988 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004989 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004990 windowInfo->applicationInfo.name.c_str(),
4991 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004992 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004993 dump += StringPrintf(", inputFeatures=%s",
4994 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004995 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004996 "ms, trustedOverlay=%s, hasToken=%s, "
4997 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004998 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004999 millis(windowInfo->dispatchingTimeout),
5000 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005001 toString(windowInfo->token != nullptr),
5002 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005003 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005004 }
5005 } else {
5006 dump += INDENT2 "Windows: <none>\n";
5007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 }
5009 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005010 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012
Michael Wright3dd60e22019-03-27 22:06:44 +00005013 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005014 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005015 const std::vector<Monitor>& monitors = it.second;
5016 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5017 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005018 }
5019 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005020 const std::vector<Monitor>& monitors = it.second;
5021 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5022 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005025 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026 }
5027
5028 nsecs_t currentTime = now();
5029
5030 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005031 if (!mRecentQueue.empty()) {
5032 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005033 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005034 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005035 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005036 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 }
5038 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005039 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 }
5041
5042 // Dump event currently being dispatched.
5043 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005044 dump += INDENT "PendingEvent:\n";
5045 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005046 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005047 dump += StringPrintf(", age=%" PRId64 "ms\n",
5048 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005050 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 }
5052
5053 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005054 if (!mInboundQueue.empty()) {
5055 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005056 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005057 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005058 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005059 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
5061 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005062 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 }
5064
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005065 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005066 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005067 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5068 const KeyReplacement& replacement = pair.first;
5069 int32_t newKeyCode = pair.second;
5070 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005071 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005072 }
5073 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005074 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005075 }
5076
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005077 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005078 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005079 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005080 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005081 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005082 connection->inputChannel->getFd().get(),
5083 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005084 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005087 if (!connection->outboundQueue.empty()) {
5088 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5089 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005090 dump += dumpQueue(connection->outboundQueue, currentTime);
5091
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005093 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 }
5095
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005096 if (!connection->waitQueue.empty()) {
5097 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5098 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005099 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005101 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 }
5103 }
5104 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005105 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 }
5107
5108 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005109 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5110 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005112 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 }
5114
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005115 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005116 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5117 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5118 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005119 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005120 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121}
5122
Michael Wright3dd60e22019-03-27 22:06:44 +00005123void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5124 const size_t numMonitors = monitors.size();
5125 for (size_t i = 0; i < numMonitors; i++) {
5126 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005127 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005128 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5129 dump += "\n";
5130 }
5131}
5132
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005133class LooperEventCallback : public LooperCallback {
5134public:
5135 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5136 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5137
5138private:
5139 std::function<int(int events)> mCallback;
5140};
5141
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005142Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005143#if DEBUG_CHANNEL_CREATION
5144 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145#endif
5146
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005147 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005148 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005149 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005150
5151 if (result) {
5152 return base::Error(result) << "Failed to open input channel pair with name " << name;
5153 }
5154
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005156 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005157 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005158 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005159 sp<Connection> connection =
5160 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005162 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5163 ALOGE("Created a new connection, but the token %p is already known", token.get());
5164 }
5165 mConnectionsByToken.emplace(token, connection);
5166
5167 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5168 this, std::placeholders::_1, token);
5169
5170 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 } // release lock
5172
5173 // Wake the looper because some connections have changed.
5174 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005175 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176}
5177
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005178Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5179 bool isGestureMonitor,
5180 const std::string& name,
5181 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005182 std::shared_ptr<InputChannel> serverChannel;
5183 std::unique_ptr<InputChannel> clientChannel;
5184 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5185 if (result) {
5186 return base::Error(result) << "Failed to open input channel pair with name " << name;
5187 }
5188
Michael Wright3dd60e22019-03-27 22:06:44 +00005189 { // acquire lock
5190 std::scoped_lock _l(mLock);
5191
5192 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005193 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5194 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005195 }
5196
Garfield Tan15601662020-09-22 15:32:38 -07005197 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005198 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005199 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005200
5201 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5202 ALOGE("Created a new connection, but the token %p is already known", token.get());
5203 }
5204 mConnectionsByToken.emplace(token, connection);
5205 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5206 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005207
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005208 auto& monitorsByDisplay =
5209 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005210 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005211
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005212 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005213 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5214 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005215 }
Garfield Tan15601662020-09-22 15:32:38 -07005216
Michael Wright3dd60e22019-03-27 22:06:44 +00005217 // Wake the looper because some connections have changed.
5218 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005219 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005220}
5221
Garfield Tan15601662020-09-22 15:32:38 -07005222status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005224 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225
Garfield Tan15601662020-09-22 15:32:38 -07005226 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 if (status) {
5228 return status;
5229 }
5230 } // release lock
5231
5232 // Wake the poll loop because removing the connection may have changed the current
5233 // synchronization state.
5234 mLooper->wake();
5235 return OK;
5236}
5237
Garfield Tan15601662020-09-22 15:32:38 -07005238status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5239 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005240 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005241 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005242 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 return BAD_VALUE;
5244 }
5245
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005246 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005247
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005249 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 }
5251
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005252 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253
5254 nsecs_t currentTime = now();
5255 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5256
5257 connection->status = Connection::STATUS_ZOMBIE;
5258 return OK;
5259}
5260
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005261void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5262 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5263 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005264}
5265
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005266void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005267 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005268 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005269 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005270 std::vector<Monitor>& monitors = it->second;
5271 const size_t numMonitors = monitors.size();
5272 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005273 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005274 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5275 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005276 monitors.erase(monitors.begin() + i);
5277 break;
5278 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005279 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005280 if (monitors.empty()) {
5281 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005282 } else {
5283 ++it;
5284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
5286}
5287
Michael Wright3dd60e22019-03-27 22:06:44 +00005288status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5289 { // acquire lock
5290 std::scoped_lock _l(mLock);
5291 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5292
5293 if (!foundDisplayId) {
5294 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5295 return BAD_VALUE;
5296 }
5297 int32_t displayId = foundDisplayId.value();
5298
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005299 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5300 mTouchStatesByDisplay.find(displayId);
5301 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005302 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5303 return BAD_VALUE;
5304 }
5305
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005306 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005307 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005308 std::optional<int32_t> foundDeviceId;
5309 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005310 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005311 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005312 foundDeviceId = state.deviceId;
5313 }
5314 }
5315 if (!foundDeviceId || !state.down) {
5316 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005317 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005318 return BAD_VALUE;
5319 }
5320 int32_t deviceId = foundDeviceId.value();
5321
5322 // Send cancel events to all the input channels we're stealing from.
5323 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005324 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005325 options.deviceId = deviceId;
5326 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005327 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005328 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005329 std::shared_ptr<InputChannel> channel =
5330 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005331 if (channel != nullptr) {
5332 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005333 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005334 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005335 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005336 canceledWindows += "]";
5337 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5338 canceledWindows.c_str());
5339
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 // Then clear the current touch state so we stop dispatching to them as well.
5341 state.filterNonMonitors();
5342 }
5343 return OK;
5344}
5345
Prabir Pradhan99987712020-11-10 18:43:05 -08005346void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5347 { // acquire lock
5348 std::scoped_lock _l(mLock);
5349 if (DEBUG_FOCUS) {
5350 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5351 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5352 windowHandle != nullptr ? windowHandle->getName().c_str()
5353 : "token without window");
5354 }
5355
Vishnu Nairc519ff72021-01-21 08:23:08 -08005356 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005357 if (focusedToken != windowToken) {
5358 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5359 enabled ? "enable" : "disable");
5360 return;
5361 }
5362
5363 if (enabled == mFocusedWindowRequestedPointerCapture) {
5364 ALOGW("Ignoring request to %s Pointer Capture: "
5365 "window has %s requested pointer capture.",
5366 enabled ? "enable" : "disable", enabled ? "already" : "not");
5367 return;
5368 }
5369
5370 mFocusedWindowRequestedPointerCapture = enabled;
5371 setPointerCaptureLocked(enabled);
5372 } // release lock
5373
5374 // Wake the thread to process command entries.
5375 mLooper->wake();
5376}
5377
Michael Wright3dd60e22019-03-27 22:06:44 +00005378std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5379 const sp<IBinder>& token) {
5380 for (const auto& it : mGestureMonitorsByDisplay) {
5381 const std::vector<Monitor>& monitors = it.second;
5382 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005383 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005384 return it.first;
5385 }
5386 }
5387 }
5388 return std::nullopt;
5389}
5390
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005391std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5392 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5393 if (gesturePid.has_value()) {
5394 return gesturePid;
5395 }
5396 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5397}
5398
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005399sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005400 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005401 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005402 }
5403
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005404 for (const auto& [token, connection] : mConnectionsByToken) {
5405 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005406 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408 }
Robert Carr4e670e52018-08-15 13:26:12 -07005409
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005410 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411}
5412
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005413std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5414 sp<Connection> connection = getConnectionLocked(connectionToken);
5415 if (connection == nullptr) {
5416 return "<nullptr>";
5417 }
5418 return connection->getInputChannelName();
5419}
5420
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005421void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005422 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005423 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005424}
5425
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005426void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5427 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005428 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005429 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5430 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 commandEntry->connection = connection;
5432 commandEntry->eventTime = currentTime;
5433 commandEntry->seq = seq;
5434 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005435 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005436 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437}
5438
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005439void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5440 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005442 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005444 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5445 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005447 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448}
5449
Vishnu Nairad321cd2020-08-20 16:40:21 -07005450void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5451 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005452 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5453 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005454 commandEntry->oldToken = oldToken;
5455 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005456 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005457}
5458
arthurhungf452d0b2021-01-06 00:19:52 +08005459void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5460 std::unique_ptr<CommandEntry> commandEntry =
5461 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5462 commandEntry->newToken = token;
5463 commandEntry->x = x;
5464 commandEntry->y = y;
5465 postCommandLocked(std::move(commandEntry));
5466}
5467
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005468void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5469 if (connection == nullptr) {
5470 LOG_ALWAYS_FATAL("Caller must check for nullness");
5471 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005472 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5473 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005474 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005475 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005476 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005477 return;
5478 }
5479 /**
5480 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5481 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5482 * has changed. This could cause newer entries to time out before the already dispatched
5483 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5484 * processes the events linearly. So providing information about the oldest entry seems to be
5485 * most useful.
5486 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005487 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005488 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5489 std::string reason =
5490 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005491 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005492 ns2ms(currentWait),
5493 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005494 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005495 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005496
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005497 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5498
5499 // Stop waking up for events on this connection, it is already unresponsive
5500 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005501}
5502
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005503void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5504 std::string reason =
5505 StringPrintf("%s does not have a focused window", application->getName().c_str());
5506 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005507
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005508 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5509 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5510 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005511 postCommandLocked(std::move(commandEntry));
5512}
5513
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005514void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5515 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5516 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5517 commandEntry->obscuringPackage = obscuringPackage;
5518 postCommandLocked(std::move(commandEntry));
5519}
5520
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005521void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5522 const std::string& reason) {
5523 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5524 updateLastAnrStateLocked(windowLabel, reason);
5525}
5526
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005527void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5528 const std::string& reason) {
5529 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005530 updateLastAnrStateLocked(windowLabel, reason);
5531}
5532
5533void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5534 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005536 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 struct tm tm;
5538 localtime_r(&t, &tm);
5539 char timestr[64];
5540 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005541 mLastAnrState.clear();
5542 mLastAnrState += INDENT "ANR:\n";
5543 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005544 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5545 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005546 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547}
5548
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005549void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 mLock.unlock();
5551
5552 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5553
5554 mLock.lock();
5555}
5556
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005557void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 sp<Connection> connection = commandEntry->connection;
5559
5560 if (connection->status != Connection::STATUS_ZOMBIE) {
5561 mLock.unlock();
5562
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005563 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564
5565 mLock.lock();
5566 }
5567}
5568
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005569void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005570 sp<IBinder> oldToken = commandEntry->oldToken;
5571 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005572 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005573 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005574 mLock.lock();
5575}
5576
arthurhungf452d0b2021-01-06 00:19:52 +08005577void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5578 sp<IBinder> newToken = commandEntry->newToken;
5579 mLock.unlock();
5580 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5581 mLock.lock();
5582}
5583
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005584void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005586
5587 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5588
5589 mLock.lock();
5590}
5591
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005592void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005593 mLock.unlock();
5594
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005595 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596
5597 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005598}
5599
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005600void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005601 mLock.unlock();
5602
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005603 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5604
5605 mLock.lock();
5606}
5607
5608void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5609 mLock.unlock();
5610
5611 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5612
5613 mLock.lock();
5614}
5615
5616void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5617 mLock.unlock();
5618
5619 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005620
5621 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005622}
5623
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005624void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5625 mLock.unlock();
5626
5627 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5628
5629 mLock.lock();
5630}
5631
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5633 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005634 KeyEntry& entry = *(commandEntry->keyEntry);
5635 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636
5637 mLock.unlock();
5638
Michael Wright2b3c3302018-03-02 17:19:13 +00005639 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005640 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005641 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005642 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5643 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005644 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646
5647 mLock.lock();
5648
5649 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005650 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005652 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005654 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5655 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657}
5658
chaviwfd6d3512019-03-25 13:23:49 -07005659void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5660 mLock.unlock();
5661 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5662 mLock.lock();
5663}
5664
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005665/**
5666 * Connection is responsive if it has no events in the waitQueue that are older than the
5667 * current time.
5668 */
5669static bool isConnectionResponsive(const Connection& connection) {
5670 const nsecs_t currentTime = now();
5671 for (const DispatchEntry* entry : connection.waitQueue) {
5672 if (entry->timeoutTime < currentTime) {
5673 return false;
5674 }
5675 }
5676 return true;
5677}
5678
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005679void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005681 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005683 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684
5685 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005686 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005687 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005688 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005690 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005691 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005692 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005693 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5694 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005695 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005696 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5697 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5698 connection->inputChannel->getConnectionToken(),
5699 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5700 finishTime);
5701 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005702
5703 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005704 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005705 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005706 restartEvent =
5707 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005708 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005709 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005710 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5711 handled);
5712 } else {
5713 restartEvent = false;
5714 }
5715
5716 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005717 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005718 // contents of the wait queue to have been drained, so we need to double-check
5719 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005720 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5721 if (dispatchEntryIt != connection->waitQueue.end()) {
5722 dispatchEntry = *dispatchEntryIt;
5723 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005724 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5725 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005726 if (!connection->responsive) {
5727 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005728 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005729 // The connection was unresponsive, and now it's responsive.
5730 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005731 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005732 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005733 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005734 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005735 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005736 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005737 } else {
5738 releaseDispatchEntry(dispatchEntry);
5739 }
5740 }
5741
5742 // Start the next dispatch cycle for this connection.
5743 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744}
5745
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005746void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5747 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5748 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5749 monitorUnresponsiveCommand->pid = pid;
5750 monitorUnresponsiveCommand->reason = std::move(reason);
5751 postCommandLocked(std::move(monitorUnresponsiveCommand));
5752}
5753
5754void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5755 std::string reason) {
5756 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5757 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5758 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5759 windowUnresponsiveCommand->reason = std::move(reason);
5760 postCommandLocked(std::move(windowUnresponsiveCommand));
5761}
5762
5763void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5764 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5765 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5766 monitorResponsiveCommand->pid = pid;
5767 postCommandLocked(std::move(monitorResponsiveCommand));
5768}
5769
5770void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5771 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5772 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5773 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5774 postCommandLocked(std::move(windowResponsiveCommand));
5775}
5776
5777/**
5778 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5779 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5780 * command entry to the command queue.
5781 */
5782void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5783 std::string reason) {
5784 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5785 if (connection.monitor) {
5786 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5787 reason.c_str());
5788 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5789 if (!pid.has_value()) {
5790 ALOGE("Could not find unresponsive monitor for connection %s",
5791 connection.inputChannel->getName().c_str());
5792 return;
5793 }
5794 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5795 return;
5796 }
5797 // If not a monitor, must be a window
5798 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5799 reason.c_str());
5800 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5801}
5802
5803/**
5804 * Tell the policy that a connection has become responsive so that it can stop ANR.
5805 */
5806void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5807 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5808 if (connection.monitor) {
5809 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5810 if (!pid.has_value()) {
5811 ALOGE("Could not find responsive monitor for connection %s",
5812 connection.inputChannel->getName().c_str());
5813 return;
5814 }
5815 sendMonitorResponsiveCommandLocked(pid.value());
5816 return;
5817 }
5818 // If not a monitor, must be a window
5819 sendWindowResponsiveCommandLocked(connectionToken);
5820}
5821
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005823 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005824 KeyEntry& keyEntry, bool handled) {
5825 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005826 if (!handled) {
5827 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005828 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005829 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005830 return false;
5831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005832
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005833 // Get the fallback key state.
5834 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005835 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005836 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005837 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005838 connection->inputState.removeFallbackKey(originalKeyCode);
5839 }
5840
5841 if (handled || !dispatchEntry->hasForegroundTarget()) {
5842 // If the application handles the original key for which we previously
5843 // generated a fallback or if the window is not a foreground window,
5844 // then cancel the associated fallback key, if any.
5845 if (fallbackKeyCode != -1) {
5846 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005848 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005849 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005850 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005852 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005853 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854
5855 mLock.unlock();
5856
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005857 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005858 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005859
5860 mLock.lock();
5861
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005862 // Cancel the fallback key.
5863 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005865 "application handled the original non-fallback key "
5866 "or is no longer a foreground target, "
5867 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868 options.keyCode = fallbackKeyCode;
5869 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005871 connection->inputState.removeFallbackKey(originalKeyCode);
5872 }
5873 } else {
5874 // If the application did not handle a non-fallback key, first check
5875 // that we are in a good state to perform unhandled key event processing
5876 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005877 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005878 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005881 "since this is not an initial down. "
5882 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005883 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005885 return false;
5886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005888 // Dispatch the unhandled key to the policy.
5889#if DEBUG_OUTBOUND_EVENT_DETAILS
5890 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005891 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005892 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005893#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005894 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005895
5896 mLock.unlock();
5897
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005898 bool fallback =
5899 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005900 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005901
5902 mLock.lock();
5903
5904 if (connection->status != Connection::STATUS_NORMAL) {
5905 connection->inputState.removeFallbackKey(originalKeyCode);
5906 return false;
5907 }
5908
5909 // Latch the fallback keycode for this key on an initial down.
5910 // The fallback keycode cannot change at any other point in the lifecycle.
5911 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005913 fallbackKeyCode = event.getKeyCode();
5914 } else {
5915 fallbackKeyCode = AKEYCODE_UNKNOWN;
5916 }
5917 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5918 }
5919
5920 ALOG_ASSERT(fallbackKeyCode != -1);
5921
5922 // Cancel the fallback key if the policy decides not to send it anymore.
5923 // We will continue to dispatch the key to the policy but we will no
5924 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005925 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5926 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005927#if DEBUG_OUTBOUND_EVENT_DETAILS
5928 if (fallback) {
5929 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005930 "as a fallback for %d, but on the DOWN it had requested "
5931 "to send %d instead. Fallback canceled.",
5932 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005933 } else {
5934 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005935 "but on the DOWN it had requested to send %d. "
5936 "Fallback canceled.",
5937 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005938 }
5939#endif
5940
5941 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5942 "canceling fallback, policy no longer desires it");
5943 options.keyCode = fallbackKeyCode;
5944 synthesizeCancelationEventsForConnectionLocked(connection, options);
5945
5946 fallback = false;
5947 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005948 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005949 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005950 }
5951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952
5953#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005954 {
5955 std::string msg;
5956 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5957 connection->inputState.getFallbackKeys();
5958 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005959 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005961 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005962 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005963 }
5964#endif
5965
5966 if (fallback) {
5967 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005968 keyEntry.eventTime = event.getEventTime();
5969 keyEntry.deviceId = event.getDeviceId();
5970 keyEntry.source = event.getSource();
5971 keyEntry.displayId = event.getDisplayId();
5972 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5973 keyEntry.keyCode = fallbackKeyCode;
5974 keyEntry.scanCode = event.getScanCode();
5975 keyEntry.metaState = event.getMetaState();
5976 keyEntry.repeatCount = event.getRepeatCount();
5977 keyEntry.downTime = event.getDownTime();
5978 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005979
5980#if DEBUG_OUTBOUND_EVENT_DETAILS
5981 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005982 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005983 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005984#endif
5985 return true; // restart the event
5986 } else {
5987#if DEBUG_OUTBOUND_EVENT_DETAILS
5988 ALOGD("Unhandled key event: No fallback key.");
5989#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005990
5991 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005992 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005993 }
5994 }
5995 return false;
5996}
5997
5998bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005999 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006000 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006001 return false;
6002}
6003
6004void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6005 mLock.unlock();
6006
Sean Stoutb4e0a592021-02-23 07:34:53 -08006007 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6008 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009
6010 mLock.lock();
6011}
6012
Michael Wrightd02c5b62014-02-10 15:10:22 -08006013void InputDispatcher::traceInboundQueueLengthLocked() {
6014 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006015 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 }
6017}
6018
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006019void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 if (ATRACE_ENABLED()) {
6021 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006022 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6023 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 }
6025}
6026
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006027void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 if (ATRACE_ENABLED()) {
6029 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006030 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6031 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 }
6033}
6034
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006035void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006036 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006038 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 dumpDispatchStateLocked(dump);
6040
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006041 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006042 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006043 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 }
6045}
6046
6047void InputDispatcher::monitor() {
6048 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006049 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006051 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052}
6053
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006054/**
6055 * Wake up the dispatcher and wait until it processes all events and commands.
6056 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6057 * this method can be safely called from any thread, as long as you've ensured that
6058 * the work you are interested in completing has already been queued.
6059 */
6060bool InputDispatcher::waitForIdle() {
6061 /**
6062 * Timeout should represent the longest possible time that a device might spend processing
6063 * events and commands.
6064 */
6065 constexpr std::chrono::duration TIMEOUT = 100ms;
6066 std::unique_lock lock(mLock);
6067 mLooper->wake();
6068 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6069 return result == std::cv_status::no_timeout;
6070}
6071
Vishnu Naire798b472020-07-23 13:52:21 -07006072/**
6073 * Sets focus to the window identified by the token. This must be called
6074 * after updating any input window handles.
6075 *
6076 * Params:
6077 * request.token - input channel token used to identify the window that should gain focus.
6078 * request.focusedToken - the token that the caller expects currently to be focused. If the
6079 * specified token does not match the currently focused window, this request will be dropped.
6080 * If the specified focused token matches the currently focused window, the call will succeed.
6081 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6082 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6083 * when requesting the focus change. This determines which request gets
6084 * precedence if there is a focus change request from another source such as pointer down.
6085 */
Vishnu Nair958da932020-08-21 17:12:37 -07006086void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6087 { // acquire lock
6088 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006089 std::optional<FocusResolver::FocusChanges> changes =
6090 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6091 if (changes) {
6092 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006093 }
6094 } // release lock
6095 // Wake up poll loop since it may need to make new input dispatching choices.
6096 mLooper->wake();
6097}
6098
Vishnu Nairc519ff72021-01-21 08:23:08 -08006099void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6100 if (changes.oldFocus) {
6101 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006102 if (focusedInputChannel) {
6103 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6104 "focus left window");
6105 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006106 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006107 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006108 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006109 if (changes.newFocus) {
6110 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006111 }
6112
Prabir Pradhan99987712020-11-10 18:43:05 -08006113 // If a window has pointer capture, then it must have focus. We need to ensure that this
6114 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6115 // If the window loses focus before it loses pointer capture, then the window can be in a state
6116 // where it has pointer capture but not focus, violating the contract. Therefore we must
6117 // dispatch the pointer capture event before the focus event. Since focus events are added to
6118 // the front of the queue (above), we add the pointer capture event to the front of the queue
6119 // after the focus events are added. This ensures the pointer capture event ends up at the
6120 // front.
6121 disablePointerCaptureForcedLocked();
6122
Vishnu Nairc519ff72021-01-21 08:23:08 -08006123 if (mFocusedDisplayId == changes.displayId) {
6124 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006125 }
6126}
Vishnu Nair958da932020-08-21 17:12:37 -07006127
Prabir Pradhan99987712020-11-10 18:43:05 -08006128void InputDispatcher::disablePointerCaptureForcedLocked() {
6129 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6130 return;
6131 }
6132
6133 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6134
6135 if (mFocusedWindowRequestedPointerCapture) {
6136 mFocusedWindowRequestedPointerCapture = false;
6137 setPointerCaptureLocked(false);
6138 }
6139
6140 if (!mWindowTokenWithPointerCapture) {
6141 // No need to send capture changes because no window has capture.
6142 return;
6143 }
6144
6145 if (mPendingEvent != nullptr) {
6146 // Move the pending event to the front of the queue. This will give the chance
6147 // for the pending event to be dropped if it is a captured event.
6148 mInboundQueue.push_front(mPendingEvent);
6149 mPendingEvent = nullptr;
6150 }
6151
6152 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6153 false /* hasCapture */);
6154 mInboundQueue.push_front(std::move(entry));
6155}
6156
Prabir Pradhan99987712020-11-10 18:43:05 -08006157void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6158 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6159 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6160 commandEntry->enabled = enabled;
6161 postCommandLocked(std::move(commandEntry));
6162}
6163
6164void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6165 android::inputdispatcher::CommandEntry* commandEntry) {
6166 mLock.unlock();
6167
6168 mPolicy->setPointerCapture(commandEntry->enabled);
6169
6170 mLock.lock();
6171}
6172
Vishnu Nair599f1412021-06-21 10:39:58 -07006173void InputDispatcher::displayRemoved(int32_t displayId) {
6174 { // acquire lock
6175 std::scoped_lock _l(mLock);
6176 // Set an empty list to remove all handles from the specific display.
6177 setInputWindowsLocked(/* window handles */ {}, displayId);
6178 setFocusedApplicationLocked(displayId, nullptr);
6179 // Call focus resolver to clean up stale requests. This must be called after input windows
6180 // have been removed for the removed display.
6181 mFocusResolver.displayRemoved(displayId);
6182 } // release lock
6183
6184 // Wake up poll loop since it may need to make new input dispatching choices.
6185 mLooper->wake();
6186}
6187
Garfield Tane84e6f92019-08-29 17:28:41 -07006188} // namespace android::inputdispatcher