blob: 070ac0a75f738fbad84eb6d0baa29149797f6416 [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
903 std::vector<TouchedMonitor> gestureMonitors =
904 findTouchedGestureMonitorsLocked(displayId, {});
905 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
906 sp<Connection> connection =
907 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000908 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700909 // This monitor could take more input. Drop all events preceding this
910 // event, so that gesture monitor could get a chance to receive the stream
911 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
912 "responsive gesture monitor that may handle the event",
913 mAwaitedFocusedApplication->getName().c_str());
914 return true;
915 }
916 }
917 }
918
919 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
920 // yet been processed by some connections, the dispatcher will wait for these motion
921 // events to be processed before dispatching the key event. This is because these motion events
922 // may cause a new window to be launched, which the user might expect to receive focus.
923 // To prevent waiting forever for such events, just send the key to the currently focused window
924 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
925 ALOGD("Received a new pointer down event, stop waiting for events to process and "
926 "just send the pending key event to the focused window.");
927 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700928 }
929 return false;
930}
931
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700932bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700933 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700934 mInboundQueue.push_back(std::move(newEntry));
935 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 traceInboundQueueLengthLocked();
937
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700938 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700939 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 // Optimize app switch latency.
941 // If the application takes too long to catch up then we drop all events preceding
942 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700943 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700945 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700947 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700948 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700952 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 mAppSwitchSawKeyDown = false;
954 needWake = true;
955 }
956 }
957 }
958 break;
959 }
960
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700961 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700962 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
963 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700964 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100968 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700969 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
970 break;
971 }
972 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800973 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700974 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800975 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
976 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700977 // nothing to do
978 break;
979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 }
981
982 return needWake;
983}
984
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700986 // Do not store sensor event in recent queue to avoid flooding the queue.
987 if (entry->type != EventEntry::Type::SENSOR) {
988 mRecentQueue.push_back(entry);
989 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700991 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 }
993}
994
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700996 int32_t y, TouchState* touchState,
997 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800998 bool addPortalWindows,
999 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001000 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
1001 LOG_ALWAYS_FATAL(
1002 "Must provide a valid touch state if adding portal windows or outside targets");
1003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -07001005 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001006 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001007 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001008 continue;
1009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1011 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001012 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013
1014 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001015 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1016 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1017 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001019 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1021 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001022 if (addPortalWindows) {
1023 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001024 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001025 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001026 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 // Found window.
1030 return windowHandle;
1031 }
1032 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001033
Michael Wright44753b12020-07-08 13:48:11 +01001034 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001035 touchState->addOrUpdateWindow(windowHandle,
1036 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1037 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
1041 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001042 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043}
1044
Garfield Tane84e6f92019-08-29 17:28:41 -07001045std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001046 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001047 std::vector<TouchedMonitor> touchedMonitors;
1048
1049 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1050 addGestureMonitors(monitors, touchedMonitors);
1051 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1052 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1053 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1055 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001056 }
1057 return touchedMonitors;
1058}
1059
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001060void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 const char* reason;
1062 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001063 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 reason = "inbound event was dropped because the policy consumed it";
1068 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001069 case DropReason::DISABLED:
1070 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 ALOGI("Dropped event because input dispatch is disabled.");
1072 }
1073 reason = "inbound event was dropped because input dispatch is disabled";
1074 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001075 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 ALOGI("Dropped event because of pending overdue app switch.");
1077 reason = "inbound event was dropped because of pending overdue app switch";
1078 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 ALOGI("Dropped event because the current application is not responding and the user "
1081 "has started interacting with a different application.");
1082 reason = "inbound event was dropped because the current application is not responding "
1083 "and the user has started interacting with a different application";
1084 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001085 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 ALOGI("Dropped event because it is stale.");
1087 reason = "inbound event was dropped because it is stale";
1088 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001089 case DropReason::NO_POINTER_CAPTURE:
1090 ALOGI("Dropped event because there is no window with Pointer Capture.");
1091 reason = "inbound event was dropped because there is no window with Pointer Capture";
1092 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 case DropReason::NOT_DROPPED: {
1094 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 }
1098
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001099 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001100 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1102 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001105 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001106 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1107 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1109 synthesizeCancelationEventsForAllConnectionsLocked(options);
1110 } else {
1111 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1112 synthesizeCancelationEventsForAllConnectionsLocked(options);
1113 }
1114 break;
1115 }
Chris Yef59a2f42020-10-16 12:55:26 -07001116 case EventEntry::Type::SENSOR: {
1117 break;
1118 }
arthurhungb89ccb02020-12-30 16:19:01 +08001119 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1120 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001121 break;
1122 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001123 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::CONFIGURATION_CHANGED:
1125 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001126 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001127 break;
1128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 }
1130}
1131
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001132static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1134 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135}
1136
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001137bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1138 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1139 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1140 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141}
1142
1143bool InputDispatcher::isAppSwitchPendingLocked() {
1144 return mAppSwitchDueTime != LONG_LONG_MAX;
1145}
1146
1147void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1148 mAppSwitchDueTime = LONG_LONG_MAX;
1149
1150#if DEBUG_APP_SWITCH
1151 if (handled) {
1152 ALOGD("App switch has arrived.");
1153 } else {
1154 ALOGD("App switch was abandoned.");
1155 }
1156#endif
1157}
1158
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001160 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161}
1162
1163bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001164 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 return false;
1166 }
1167
1168 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001169 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001170 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001172 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173
1174 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001175 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 return true;
1177}
1178
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001179void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1180 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181}
1182
1183void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001184 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001185 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001186 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 releaseInboundEventLocked(entry);
1188 }
1189 traceInboundQueueLengthLocked();
1190}
1191
1192void InputDispatcher::releasePendingEventLocked() {
1193 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001195 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
1197}
1198
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001201 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202#if DEBUG_DISPATCH_CYCLE
1203 ALOGD("Injected inbound event was dropped.");
1204#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001205 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001208 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 }
1210 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211}
1212
1213void InputDispatcher::resetKeyRepeatLocked() {
1214 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001215 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 }
1217}
1218
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001219std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1220 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221
Michael Wright2e732952014-09-24 13:26:59 -07001222 uint32_t policyFlags = entry->policyFlags &
1223 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225 std::shared_ptr<KeyEntry> newEntry =
1226 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1227 entry->source, entry->displayId, policyFlags, entry->action,
1228 entry->flags, entry->keyCode, entry->scanCode,
1229 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231 newEntry->syntheticRepeat = true;
1232 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001234 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235}
1236
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001240 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241#endif
1242
1243 // Reset key repeating in case a keyboard device was added or removed or something.
1244 resetKeyRepeatLocked();
1245
1246 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001247 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1248 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001250 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 return true;
1252}
1253
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1255 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1258 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259#endif
1260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 synthesizeCancelationEventsForAllConnectionsLocked(options);
1264 return true;
1265}
1266
Vishnu Nairad321cd2020-08-20 16:40:21 -07001267void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001268 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001269 if (mPendingEvent != nullptr) {
1270 // Move the pending event to the front of the queue. This will give the chance
1271 // for the pending event to get dispatched to the newly focused window
1272 mInboundQueue.push_front(mPendingEvent);
1273 mPendingEvent = nullptr;
1274 }
1275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001276 std::unique_ptr<FocusEntry> focusEntry =
1277 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1278 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001279
1280 // This event should go to the front of the queue, but behind all other focus events
1281 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001283 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284 [](const std::shared_ptr<EventEntry>& event) {
1285 return event->type == EventEntry::Type::FOCUS;
1286 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001287
1288 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001290}
1291
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001293 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001294 if (channel == nullptr) {
1295 return; // Window has gone away
1296 }
1297 InputTarget target;
1298 target.inputChannel = channel;
1299 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1300 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001301 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1302 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001303 std::string reason = std::string("reason=").append(entry->reason);
1304 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001305 dispatchEventLocked(currentTime, entry, {target});
1306}
1307
Prabir Pradhan99987712020-11-10 18:43:05 -08001308void InputDispatcher::dispatchPointerCaptureChangedLocked(
1309 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1310 DropReason& dropReason) {
1311 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001312 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1313 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1314 }
1315 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001316 // Pointer capture was already forcefully disabled because of focus change.
1317 dropReason = DropReason::NOT_DROPPED;
1318 return;
1319 }
1320
1321 // Set drop reason for early returns
1322 dropReason = DropReason::NO_POINTER_CAPTURE;
1323
1324 sp<IBinder> token;
1325 if (entry->pointerCaptureEnabled) {
1326 // Enable Pointer Capture
1327 if (!mFocusedWindowRequestedPointerCapture) {
1328 // This can happen if a window requests capture and immediately releases capture.
1329 ALOGW("No window requested Pointer Capture.");
1330 return;
1331 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001332 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001333 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1334 mWindowTokenWithPointerCapture = token;
1335 } else {
1336 // Disable Pointer Capture
1337 token = mWindowTokenWithPointerCapture;
1338 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001339 if (mFocusedWindowRequestedPointerCapture) {
1340 mFocusedWindowRequestedPointerCapture = false;
1341 setPointerCaptureLocked(false);
1342 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001343 }
1344
1345 auto channel = getInputChannelLocked(token);
1346 if (channel == nullptr) {
1347 // Window has gone away, clean up Pointer Capture state.
1348 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001349 if (mFocusedWindowRequestedPointerCapture) {
1350 mFocusedWindowRequestedPointerCapture = false;
1351 setPointerCaptureLocked(false);
1352 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001353 return;
1354 }
1355 InputTarget target;
1356 target.inputChannel = channel;
1357 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1358 entry->dispatchInProgress = true;
1359 dispatchEventLocked(currentTime, entry, {target});
1360
1361 dropReason = DropReason::NOT_DROPPED;
1362}
1363
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001364bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001367 if (!entry->dispatchInProgress) {
1368 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1369 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1370 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1371 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001372 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 // We have seen two identical key downs in a row which indicates that the device
1374 // driver is automatically generating key repeats itself. We take note of the
1375 // repeat here, but we disable our own next key repeat timer since it is clear that
1376 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001377 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1378 // Make sure we don't get key down from a different device. If a different
1379 // device Id has same key pressed down, the new device Id will replace the
1380 // current one to hold the key repeat with repeat count reset.
1381 // In the future when got a KEY_UP on the device id, drop it and do not
1382 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1384 resetKeyRepeatLocked();
1385 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1386 } else {
1387 // Not a repeat. Save key down state in case we do see a repeat later.
1388 resetKeyRepeatLocked();
1389 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1390 }
1391 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001392 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1393 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001394 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001395#if DEBUG_INBOUND_EVENT_DETAILS
1396 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1397#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001398 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 resetKeyRepeatLocked();
1400 }
1401
1402 if (entry->repeatCount == 1) {
1403 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1404 } else {
1405 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1406 }
1407
1408 entry->dispatchInProgress = true;
1409
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001410 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412
1413 // Handle case where the policy asked us to try again later last time.
1414 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1415 if (currentTime < entry->interceptKeyWakeupTime) {
1416 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1417 *nextWakeupTime = entry->interceptKeyWakeupTime;
1418 }
1419 return false; // wait until next wakeup
1420 }
1421 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1422 entry->interceptKeyWakeupTime = 0;
1423 }
1424
1425 // Give the policy a chance to intercept the key.
1426 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1427 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001428 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001429 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001430 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001431 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001432 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001434 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 return false; // wait for the command to run
1436 } else {
1437 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1438 }
1439 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001440 if (*dropReason == DropReason::NOT_DROPPED) {
1441 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 }
1443 }
1444
1445 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001446 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001447 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001448 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1449 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001450 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return true;
1452 }
1453
1454 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001455 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001456 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001457 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001458 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 return false;
1460 }
1461
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001462 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001463 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 return true;
1465 }
1466
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001467 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469
1470 // Dispatch the key.
1471 dispatchEventLocked(currentTime, entry, inputTargets);
1472 return true;
1473}
1474
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001475void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001477 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1479 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1481 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1482 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483#endif
1484}
1485
Chris Yef59a2f42020-10-16 12:55:26 -07001486void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1487 mLock.unlock();
1488
1489 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1490 if (entry->accuracyChanged) {
1491 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1492 }
1493 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1494 entry->hwTimestamp, entry->values);
1495 mLock.lock();
1496}
1497
1498void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1499 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1500#if DEBUG_OUTBOUND_EVENT_DETAILS
1501 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1502 "source=0x%x, sensorType=%s",
1503 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001504 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001505#endif
1506 std::unique_ptr<CommandEntry> commandEntry =
1507 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1508 commandEntry->sensorEntry = entry;
1509 postCommandLocked(std::move(commandEntry));
1510}
1511
1512bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1513#if DEBUG_OUTBOUND_EVENT_DETAILS
1514 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1515 NamedEnum::string(sensorType).c_str());
1516#endif
1517 { // acquire lock
1518 std::scoped_lock _l(mLock);
1519
1520 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1521 std::shared_ptr<EventEntry> entry = *it;
1522 if (entry->type == EventEntry::Type::SENSOR) {
1523 it = mInboundQueue.erase(it);
1524 releaseInboundEventLocked(entry);
1525 }
1526 }
1527 }
1528 return true;
1529}
1530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001532 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001533 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001535 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 entry->dispatchInProgress = true;
1537
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 }
1540
1541 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001542 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001543 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001544 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1545 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 return true;
1547 }
1548
1549 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1550
1551 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001552 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553
1554 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 if (isPointerEvent) {
1557 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001559 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001560 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 } else {
1562 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001564 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 return false;
1568 }
1569
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001570 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001572 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1573 return true;
1574 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001575 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001576 CancelationOptions::Mode mode(isPointerEvent
1577 ? CancelationOptions::CANCEL_POINTER_EVENTS
1578 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1579 CancelationOptions options(mode, "input event injection failed");
1580 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 return true;
1582 }
1583
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001584 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001585 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001587 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001588 std::unordered_map<int32_t, TouchState>::iterator it =
1589 mTouchStatesByDisplay.find(entry->displayId);
1590 if (it != mTouchStatesByDisplay.end()) {
1591 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001592 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001593 // The event has gone through these portal windows, so we add monitoring targets of
1594 // the corresponding displays as well.
1595 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001596 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001597 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001598 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001599 }
1600 }
1601 }
1602 }
1603
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 // Dispatch the motion.
1605 if (conflictingPointerActions) {
1606 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001607 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 synthesizeCancelationEventsForAllConnectionsLocked(options);
1609 }
1610 dispatchEventLocked(currentTime, entry, inputTargets);
1611 return true;
1612}
1613
arthurhungb89ccb02020-12-30 16:19:01 +08001614void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1615 bool isExiting, const MotionEntry& motionEntry) {
1616 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1617 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1618 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1619 PointerCoords pointerCoords;
1620 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1621 pointerCoords.transform(windowHandle->getInfo()->transform);
1622
1623 std::unique_ptr<DragEntry> dragEntry =
1624 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1625 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1626 pointerCoords.getY());
1627
1628 enqueueInboundEventLocked(std::move(dragEntry));
1629}
1630
1631void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1632 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1633 if (channel == nullptr) {
1634 return; // Window has gone away
1635 }
1636 InputTarget target;
1637 target.inputChannel = channel;
1638 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1639 entry->dispatchInProgress = true;
1640 dispatchEventLocked(currentTime, entry, {target});
1641}
1642
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001643void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001645 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 ", policyFlags=0x%x, "
1647 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1648 "metaState=0x%x, buttonState=0x%x,"
1649 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1651 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1652 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001656 "x=%f, y=%f, pressure=%f, size=%f, "
1657 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1658 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001659 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1660 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1661 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1662 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1663 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1664 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1665 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1666 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1667 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1668 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670#endif
1671}
1672
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001673void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1674 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001676 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677#if DEBUG_DISPATCH_CYCLE
1678 ALOGD("dispatchEventToCurrentInputTargets");
1679#endif
1680
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001681 updateInteractionTokensLocked(*eventEntry, inputTargets);
1682
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1684
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001685 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001687 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001688 sp<Connection> connection =
1689 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001690 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001691 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001693 if (DEBUG_FOCUS) {
1694 ALOGD("Dropping event delivery to target with channel '%s' because it "
1695 "is no longer registered with the input dispatcher.",
1696 inputTarget.inputChannel->getName().c_str());
1697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 }
1699 }
1700}
1701
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001702void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1703 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1704 // If the policy decides to close the app, we will get a channel removal event via
1705 // unregisterInputChannel, and will clean up the connection that way. We are already not
1706 // sending new pointers to the connection when it blocked, but focused events will continue to
1707 // pile up.
1708 ALOGW("Canceling events for %s because it is unresponsive",
1709 connection->inputChannel->getName().c_str());
1710 if (connection->status == Connection::STATUS_NORMAL) {
1711 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1712 "application not responding");
1713 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 }
1715}
1716
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001717void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001718 if (DEBUG_FOCUS) {
1719 ALOGD("Resetting ANR timeouts.");
1720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721
1722 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001723 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001724 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725}
1726
Tiger Huang721e26f2018-07-24 22:26:19 +08001727/**
1728 * Get the display id that the given event should go to. If this event specifies a valid display id,
1729 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1730 * Focused display is the display that the user most recently interacted with.
1731 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001732int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001733 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001735 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1737 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 break;
1739 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001740 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001741 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1742 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001743 break;
1744 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001745 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001746 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001747 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001748 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001749 case EventEntry::Type::SENSOR:
1750 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001751 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 return ADISPLAY_ID_NONE;
1753 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001754 }
1755 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1756}
1757
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001758bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1759 const char* focusedWindowName) {
1760 if (mAnrTracker.empty()) {
1761 // already processed all events that we waited for
1762 mKeyIsWaitingForEventsTimeout = std::nullopt;
1763 return false;
1764 }
1765
1766 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1767 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001768 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001769 mKeyIsWaitingForEventsTimeout = currentTime +
1770 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1771 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772 return true;
1773 }
1774
1775 // We still have pending events, and already started the timer
1776 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1777 return true; // Still waiting
1778 }
1779
1780 // Waited too long, and some connection still hasn't processed all motions
1781 // Just send the key to the focused window
1782 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1783 focusedWindowName);
1784 mKeyIsWaitingForEventsTimeout = std::nullopt;
1785 return false;
1786}
1787
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001788InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1789 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1790 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001791 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792
Tiger Huang721e26f2018-07-24 22:26:19 +08001793 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001794 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001795 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001796 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1797
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 // If there is no currently focused window and no focused application
1799 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001800 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1801 ALOGI("Dropping %s event because there is no focused window or focused application in "
1802 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001803 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 }
1806
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001807 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1808 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1809 // start interacting with another application via touch (app switch). This code can be removed
1810 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1811 // an app is expected to have a focused window.
1812 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1813 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1814 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001815 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1816 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1817 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001819 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001820 ALOGW("Waiting because no window has focus but %s may eventually add a "
1821 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001822 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001824 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001825 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1826 // Already raised ANR. Drop the event
1827 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001828 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001829 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001830 } else {
1831 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833 }
1834 }
1835
1836 // we have a valid, non-null focused window
1837 resetNoFocusedWindowTimeoutLocked();
1838
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001840 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001841 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 }
1843
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001844 if (focusedWindowHandle->getInfo()->paused) {
1845 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001846 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001847 }
1848
1849 // If the event is a key event, then we must wait for all previous events to
1850 // complete before delivering it because previous events may have the
1851 // side-effect of transferring focus to a different window and we want to
1852 // ensure that the following keys are sent to the new window.
1853 //
1854 // Suppose the user touches a button in a window then immediately presses "A".
1855 // If the button causes a pop-up window to appear then we want to ensure that
1856 // the "A" key is delivered to the new pop-up window. This is because users
1857 // often anticipate pending UI changes when typing on a keyboard.
1858 // To obtain this behavior, we must serialize key events with respect to all
1859 // prior input events.
1860 if (entry.type == EventEntry::Type::KEY) {
1861 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1862 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866
1867 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001868 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001869 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1870 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871
1872 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001873 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874}
1875
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001876/**
1877 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1878 * that are currently unresponsive.
1879 */
1880std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1881 const std::vector<TouchedMonitor>& monitors) const {
1882 std::vector<TouchedMonitor> responsiveMonitors;
1883 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1884 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1885 sp<Connection> connection = getConnectionLocked(
1886 monitor.monitor.inputChannel->getConnectionToken());
1887 if (connection == nullptr) {
1888 ALOGE("Could not find connection for monitor %s",
1889 monitor.monitor.inputChannel->getName().c_str());
1890 return false;
1891 }
1892 if (!connection->responsive) {
1893 ALOGW("Unresponsive monitor %s will not get the new gesture",
1894 connection->inputChannel->getName().c_str());
1895 return false;
1896 }
1897 return true;
1898 });
1899 return responsiveMonitors;
1900}
1901
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001902InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1903 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1904 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001905 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 enum InjectionPermission {
1907 INJECTION_PERMISSION_UNKNOWN,
1908 INJECTION_PERMISSION_GRANTED,
1909 INJECTION_PERMISSION_DENIED
1910 };
1911
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 // For security reasons, we defer updating the touch state until we are sure that
1913 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001914 int32_t displayId = entry.displayId;
1915 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1917
1918 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001919 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001921 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1922 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001924 // Copy current touch state into tempTouchState.
1925 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1926 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001927 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001928 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001929 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1930 mTouchStatesByDisplay.find(displayId);
1931 if (oldStateIt != mTouchStatesByDisplay.end()) {
1932 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001933 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001934 }
1935
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001936 bool isSplit = tempTouchState.split;
1937 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1938 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1939 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001940 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1941 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1942 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1943 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1944 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001945 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 bool wrongDevice = false;
1947 if (newGesture) {
1948 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001949 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001950 ALOGI("Dropping event because a pointer for a different device is already down "
1951 "in display %" PRId32,
1952 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001953 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001954 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 switchedDevice = false;
1956 wrongDevice = true;
1957 goto Failed;
1958 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001959 tempTouchState.reset();
1960 tempTouchState.down = down;
1961 tempTouchState.deviceId = entry.deviceId;
1962 tempTouchState.source = entry.source;
1963 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001965 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001966 ALOGI("Dropping move event because a pointer for a different device is already active "
1967 "in display %" PRId32,
1968 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001969 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001971 switchedDevice = false;
1972 wrongDevice = true;
1973 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 }
1975
1976 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1977 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1978
Garfield Tan00f511d2019-06-12 16:55:40 -07001979 int32_t x;
1980 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001982 // Always dispatch mouse events to cursor position.
1983 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001984 x = int32_t(entry.xCursorPosition);
1985 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001986 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1988 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001989 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001990 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001991 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001992 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1993 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001994
1995 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001996 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001997 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002000 if (newTouchedWindowHandle != nullptr &&
2001 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002002 // New window supports splitting, but we should never split mouse events.
2003 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 } else if (isSplit) {
2005 // New window does not support splitting but we have already split events.
2006 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002007 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009
2010 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002011 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002013 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002014 }
2015
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002016 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2017 ALOGI("Not sending touch event to %s because it is paused",
2018 newTouchedWindowHandle->getName().c_str());
2019 newTouchedWindowHandle = nullptr;
2020 }
2021
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002022 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002024 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2025 if (!isResponsive) {
2026 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2028 newTouchedWindowHandle = nullptr;
2029 }
2030 }
2031
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002032 // Drop events that can't be trusted due to occlusion
2033 if (newTouchedWindowHandle != nullptr &&
2034 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2035 TouchOcclusionInfo occlusionInfo =
2036 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002037 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002038 if (DEBUG_TOUCH_OCCLUSION) {
2039 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2040 for (const auto& log : occlusionInfo.debugInfo) {
2041 ALOGD("%s", log.c_str());
2042 }
2043 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002044 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2045 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2046 ALOGW("Dropping untrusted touch event due to %s/%d",
2047 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2048 newTouchedWindowHandle = nullptr;
2049 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002050 }
2051 }
2052
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002053 // Also don't send the new touch event to unresponsive gesture monitors
2054 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2055
Michael Wright3dd60e22019-03-27 22:06:44 +00002056 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2057 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002058 "(%d, %d) in display %" PRId32 ".",
2059 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002060 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002061 goto Failed;
2062 }
2063
2064 if (newTouchedWindowHandle != nullptr) {
2065 // Set target flags.
2066 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2067 if (isSplit) {
2068 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002070 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2071 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2072 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2073 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2074 }
2075
2076 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002077 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2078 newHoverWindowHandle = nullptr;
2079 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002080 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 }
2082
2083 // Update the temporary touch state.
2084 BitSet32 pointerIds;
2085 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002086 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002087 pointerIds.markBit(pointerId);
2088 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002089 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002092 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 } else {
2094 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2095
2096 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002097 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002098 if (DEBUG_FOCUS) {
2099 ALOGD("Dropping event because the pointer is not down or we previously "
2100 "dropped the pointer down event in display %" PRId32,
2101 displayId);
2102 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002103 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 goto Failed;
2105 }
2106
arthurhung6d4bed92021-03-17 11:59:33 +08002107 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002108
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002110 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002111 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002112 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2113 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114
2115 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002116 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002117 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002118 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2119 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002120 if (DEBUG_FOCUS) {
2121 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2122 oldTouchedWindowHandle->getName().c_str(),
2123 newTouchedWindowHandle->getName().c_str(), displayId);
2124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002126 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2127 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2128 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129
2130 // Make a slippery entrance into the new window.
2131 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2132 isSplit = true;
2133 }
2134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002135 int32_t targetFlags =
2136 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 if (isSplit) {
2138 targetFlags |= InputTarget::FLAG_SPLIT;
2139 }
2140 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2141 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002142 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2143 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 }
2145
2146 BitSet32 pointerIds;
2147 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002148 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002150 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 }
2152 }
2153 }
2154
2155 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002156 // Let the previous window know that the hover sequence is over, unless we already did it
2157 // when dispatching it as is to newTouchedWindowHandle.
2158 if (mLastHoverWindowHandle != nullptr &&
2159 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2160 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161#if DEBUG_HOVER
2162 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002163 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002165 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2166 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 }
2168
Garfield Tandf26e862020-07-01 20:18:19 -07002169 // Let the new window know that the hover sequence is starting, unless we already did it
2170 // when dispatching it as is to newTouchedWindowHandle.
2171 if (newHoverWindowHandle != nullptr &&
2172 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2173 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174#if DEBUG_HOVER
2175 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002176 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2179 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2180 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
2182 }
2183
2184 // Check permission to inject into all touched foreground windows and ensure there
2185 // is at least one touched foreground window.
2186 {
2187 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2190 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002191 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002192 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 injectionPermission = INJECTION_PERMISSION_DENIED;
2194 goto Failed;
2195 }
2196 }
2197 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002198 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002199 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002200 ALOGI("Dropping event because there is no touched foreground window in display "
2201 "%" PRId32 " or gesture monitor to receive it.",
2202 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002203 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 goto Failed;
2205 }
2206
2207 // Permission granted to injection into all touched foreground windows.
2208 injectionPermission = INJECTION_PERMISSION_GRANTED;
2209 }
2210
2211 // Check whether windows listening for outside touches are owned by the same UID. If it is
2212 // set the policy flag that we will not reveal coordinate information to this window.
2213 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2214 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002215 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002216 if (foregroundWindowHandle) {
2217 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002219 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2220 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2221 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002222 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2223 InputTarget::FLAG_ZERO_COORDS,
2224 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 }
2227 }
2228 }
2229 }
2230
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 // If this is the first pointer going down and the touched window has a wallpaper
2232 // then also add the touched wallpaper windows so they are locked in for the duration
2233 // of the touch gesture.
2234 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2235 // engine only supports touch events. We would need to add a mechanism similar
2236 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2237 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2238 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002239 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002240 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002241 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002242 getWindowHandlesLocked(displayId);
2243 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002245 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002246 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 .addOrUpdateWindow(windowHandle,
2249 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2250 InputTarget::
2251 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2252 InputTarget::FLAG_DISPATCH_AS_IS,
2253 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
2255 }
2256 }
2257 }
2258
2259 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002260 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002262 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002268 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002270 }
2271
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 // Drop the outside or hover touch windows since we will not care about them
2273 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002274 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275
2276Failed:
2277 // Check injection permission once and for all.
2278 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002279 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 injectionPermission = INJECTION_PERMISSION_GRANTED;
2281 } else {
2282 injectionPermission = INJECTION_PERMISSION_DENIED;
2283 }
2284 }
2285
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002286 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2287 return injectionResult;
2288 }
2289
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002291 if (!wrongDevice) {
2292 if (switchedDevice) {
2293 if (DEBUG_FOCUS) {
2294 ALOGD("Conflicting pointer actions: Switched to a different device.");
2295 }
2296 *outConflictingPointerActions = true;
2297 }
2298
2299 if (isHoverAction) {
2300 // Started hovering, therefore no longer down.
2301 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002302 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002303 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2304 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 *outConflictingPointerActions = true;
2307 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002308 tempTouchState.reset();
2309 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2310 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2311 tempTouchState.deviceId = entry.deviceId;
2312 tempTouchState.source = entry.source;
2313 tempTouchState.displayId = displayId;
2314 }
2315 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2316 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2317 // All pointers up or canceled.
2318 tempTouchState.reset();
2319 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2320 // First pointer went down.
2321 if (oldState && oldState->down) {
2322 if (DEBUG_FOCUS) {
2323 ALOGD("Conflicting pointer actions: Down received while already down.");
2324 }
2325 *outConflictingPointerActions = true;
2326 }
2327 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2328 // One pointer went up.
2329 if (isSplit) {
2330 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2331 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002333 for (size_t i = 0; i < tempTouchState.windows.size();) {
2334 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2335 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2336 touchedWindow.pointerIds.clearBit(pointerId);
2337 if (touchedWindow.pointerIds.isEmpty()) {
2338 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2339 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002342 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002344 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002345 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002346
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002347 // Save changes unless the action was scroll in which case the temporary touch
2348 // state was only valid for this one action.
2349 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2350 if (tempTouchState.displayId >= 0) {
2351 mTouchStatesByDisplay[displayId] = tempTouchState;
2352 } else {
2353 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002357 // Update hover state.
2358 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
2360
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 return injectionResult;
2362}
2363
arthurhung6d4bed92021-03-17 11:59:33 +08002364void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2365 const sp<InputWindowHandle> dropWindow =
2366 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2367 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2368 true /*ignoreDragWindow*/);
2369 if (dropWindow) {
2370 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2371 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002372 } else {
2373 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002374 }
2375 mDragState.reset();
2376}
2377
2378void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2379 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002380 return;
2381 }
2382
arthurhung6d4bed92021-03-17 11:59:33 +08002383 if (!mDragState->isStartDrag) {
2384 mDragState->isStartDrag = true;
2385 mDragState->isStylusButtonDownAtStart =
2386 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2387 }
2388
arthurhungb89ccb02020-12-30 16:19:01 +08002389 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2390 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2391 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2392 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002393 // Handle the special case : stylus button no longer pressed.
2394 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2395 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2396 finishDragAndDrop(entry.displayId, x, y);
2397 return;
2398 }
2399
arthurhungb89ccb02020-12-30 16:19:01 +08002400 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002401 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002402 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2403 true /*ignoreDragWindow*/);
2404 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002405 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2406 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2407 if (mDragState->dragHoverWindowHandle != nullptr) {
2408 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2409 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002410 }
arthurhung6d4bed92021-03-17 11:59:33 +08002411 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002412 }
2413 // enqueue drag location if needed.
2414 if (hoverWindowHandle != nullptr) {
2415 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2416 }
arthurhung6d4bed92021-03-17 11:59:33 +08002417 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2418 finishDragAndDrop(entry.displayId, x, y);
2419 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002420 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002421 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002422 }
2423}
2424
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002426 int32_t targetFlags, BitSet32 pointerIds,
2427 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002428 std::vector<InputTarget>::iterator it =
2429 std::find_if(inputTargets.begin(), inputTargets.end(),
2430 [&windowHandle](const InputTarget& inputTarget) {
2431 return inputTarget.inputChannel->getConnectionToken() ==
2432 windowHandle->getToken();
2433 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002434
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002435 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002436
2437 if (it == inputTargets.end()) {
2438 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002439 std::shared_ptr<InputChannel> inputChannel =
2440 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002441 if (inputChannel == nullptr) {
2442 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2443 return;
2444 }
2445 inputTarget.inputChannel = inputChannel;
2446 inputTarget.flags = targetFlags;
2447 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002448 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002449 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002450 inputTargets.push_back(inputTarget);
2451 it = inputTargets.end() - 1;
2452 }
2453
2454 ALOG_ASSERT(it->flags == targetFlags);
2455 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2456
chaviw1ff3d1e2020-07-01 15:53:47 -07002457 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458}
2459
Michael Wright3dd60e22019-03-27 22:06:44 +00002460void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 int32_t displayId, float xOffset,
2462 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002463 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2464 mGlobalMonitorsByDisplay.find(displayId);
2465
2466 if (it != mGlobalMonitorsByDisplay.end()) {
2467 const std::vector<Monitor>& monitors = it->second;
2468 for (const Monitor& monitor : monitors) {
2469 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
2472}
2473
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002474void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2475 float yOffset,
2476 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002477 InputTarget target;
2478 target.inputChannel = monitor.inputChannel;
2479 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002480 ui::Transform t;
2481 t.set(xOffset, yOffset);
2482 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002483 inputTargets.push_back(target);
2484}
2485
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 const InjectionState* injectionState) {
2488 if (injectionState &&
2489 (windowHandle == nullptr ||
2490 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2491 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002492 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002494 "owned by uid %d",
2495 injectionState->injectorPid, injectionState->injectorUid,
2496 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 } else {
2498 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 }
2501 return false;
2502 }
2503 return true;
2504}
2505
Robert Carrc9bf1d32020-04-13 17:21:08 -07002506/**
2507 * Indicate whether one window handle should be considered as obscuring
2508 * another window handle. We only check a few preconditions. Actually
2509 * checking the bounds is left to the caller.
2510 */
2511static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2512 const sp<InputWindowHandle>& otherHandle) {
2513 // Compare by token so cloned layers aren't counted
2514 if (haveSameToken(windowHandle, otherHandle)) {
2515 return false;
2516 }
2517 auto info = windowHandle->getInfo();
2518 auto otherInfo = otherHandle->getInfo();
2519 if (!otherInfo->visible) {
2520 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002521 } else if (otherInfo->alpha == 0 &&
2522 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2523 // Those act as if they were invisible, so we don't need to flag them.
2524 // We do want to potentially flag touchable windows even if they have 0
2525 // opacity, since they can consume touches and alter the effects of the
2526 // user interaction (eg. apps that rely on
2527 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2528 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2529 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002530 } else if (info->ownerUid == otherInfo->ownerUid) {
2531 // If ownerUid is the same we don't generate occlusion events as there
2532 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002533 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002534 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002535 return false;
2536 } else if (otherInfo->displayId != info->displayId) {
2537 return false;
2538 }
2539 return true;
2540}
2541
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002542/**
2543 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2544 * untrusted, one should check:
2545 *
2546 * 1. If result.hasBlockingOcclusion is true.
2547 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2548 * BLOCK_UNTRUSTED.
2549 *
2550 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2551 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2552 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2553 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2554 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2555 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2556 *
2557 * If neither of those is true, then it means the touch can be allowed.
2558 */
2559InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2560 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002561 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2562 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002563 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2564 TouchOcclusionInfo info;
2565 info.hasBlockingOcclusion = false;
2566 info.obscuringOpacity = 0;
2567 info.obscuringUid = -1;
2568 std::map<int32_t, float> opacityByUid;
2569 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2570 if (windowHandle == otherHandle) {
2571 break; // All future windows are below us. Exit early.
2572 }
2573 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002574 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2575 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002576 if (DEBUG_TOUCH_OCCLUSION) {
2577 info.debugInfo.push_back(
2578 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2579 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002580 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2581 // we perform the checks below to see if the touch can be propagated or not based on the
2582 // window's touch occlusion mode
2583 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2584 info.hasBlockingOcclusion = true;
2585 info.obscuringUid = otherInfo->ownerUid;
2586 info.obscuringPackage = otherInfo->packageName;
2587 break;
2588 }
2589 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2590 uint32_t uid = otherInfo->ownerUid;
2591 float opacity =
2592 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2593 // Given windows A and B:
2594 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2595 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2596 opacityByUid[uid] = opacity;
2597 if (opacity > info.obscuringOpacity) {
2598 info.obscuringOpacity = opacity;
2599 info.obscuringUid = uid;
2600 info.obscuringPackage = otherInfo->packageName;
2601 }
2602 }
2603 }
2604 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002605 if (DEBUG_TOUCH_OCCLUSION) {
2606 info.debugInfo.push_back(
2607 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2608 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002609 return info;
2610}
2611
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002612std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2613 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002614 return StringPrintf(INDENT2
2615 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2616 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2617 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2618 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002619 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002620 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002621 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002622 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2623 info->frameTop, info->frameRight, info->frameBottom,
2624 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002625 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2626 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2627 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002628}
2629
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002630bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2631 if (occlusionInfo.hasBlockingOcclusion) {
2632 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2633 occlusionInfo.obscuringUid);
2634 return false;
2635 }
2636 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2637 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2638 "%.2f, maximum allowed = %.2f)",
2639 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2640 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2641 return false;
2642 }
2643 return true;
2644}
2645
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2647 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002649 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002650 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002651 if (windowHandle == otherHandle) {
2652 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002655 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002656 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 return true;
2658 }
2659 }
2660 return false;
2661}
2662
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002663bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2664 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002665 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002666 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002667 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002668 if (windowHandle == otherHandle) {
2669 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002670 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002671 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002672 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002673 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002674 return true;
2675 }
2676 }
2677 return false;
2678}
2679
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002680std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002681 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002683 if (applicationHandle != nullptr) {
2684 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002685 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 } else {
2687 return applicationHandle->getName();
2688 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002689 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002690 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002692 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 }
2694}
2695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002696void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002697 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002698 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2699 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002700 // Focus or pointer capture changed events are passed to apps, but do not represent user
2701 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002702 return;
2703 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002704 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002705 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002706 if (focusedWindowHandle != nullptr) {
2707 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002708 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002710 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711#endif
2712 return;
2713 }
2714 }
2715
2716 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002717 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002718 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002719 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2720 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 return;
2722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002724 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 eventType = USER_ACTIVITY_EVENT_TOUCH;
2726 }
2727 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002729 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002730 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2731 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 return;
2733 }
2734 eventType = USER_ACTIVITY_EVENT_BUTTON;
2735 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002737 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002738 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002739 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002740 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002741 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2742 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002743 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002744 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002745 break;
2746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 }
2748
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002749 std::unique_ptr<CommandEntry> commandEntry =
2750 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002751 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002753 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002754 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755}
2756
2757void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002758 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002759 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002760 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002761 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002763 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002764 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002765 ATRACE_NAME(message.c_str());
2766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767#if DEBUG_DISPATCH_CYCLE
2768 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002769 "globalScaleFactor=%f, pointerIds=0x%x %s",
2770 connection->getInputChannelName().c_str(), inputTarget.flags,
2771 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2772 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773#endif
2774
2775 // Skip this event if the connection status is not normal.
2776 // We don't want to enqueue additional outbound events if the connection is broken.
2777 if (connection->status != Connection::STATUS_NORMAL) {
2778#if DEBUG_DISPATCH_CYCLE
2779 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781#endif
2782 return;
2783 }
2784
2785 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002786 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2787 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2788 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002789 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002791 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002792 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002793 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002794 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 if (!splitMotionEntry) {
2796 return; // split event was dropped
2797 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002798 if (DEBUG_FOCUS) {
2799 ALOGD("channel '%s' ~ Split motion event.",
2800 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002801 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002802 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002803 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2804 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 return;
2806 }
2807 }
2808
2809 // Not splitting. Enqueue dispatch entries for the event as is.
2810 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2811}
2812
2813void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002814 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002815 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002816 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002817 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002819 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002820 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002821 ATRACE_NAME(message.c_str());
2822 }
2823
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002824 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825
2826 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002829 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002831 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002833 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002835 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002837 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839
2840 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002841 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 startDispatchCycleLocked(currentTime, connection);
2843 }
2844}
2845
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002847 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002848 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002850 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2852 connection->getInputChannelName().c_str(),
2853 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002854 ATRACE_NAME(message.c_str());
2855 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002856 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 if (!(inputTargetFlags & dispatchMode)) {
2858 return;
2859 }
2860 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2861
2862 // This is a new event.
2863 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002864 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002865 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002867 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2868 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002869 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002871 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002872 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002873 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002874 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002875 dispatchEntry->resolvedAction = keyEntry.action;
2876 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2879 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2882 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 return; // skip the inconsistent event
2885 }
2886 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002889 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002890 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002891 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2892 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2893 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2894 static_cast<int32_t>(IdGenerator::Source::OTHER);
2895 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2897 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2898 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2899 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2900 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2901 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2902 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2903 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2904 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2905 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2906 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002907 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002908 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 }
2910 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002911 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2912 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2915 "event",
2916 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002918 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2919 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002923 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2925 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2926 }
2927 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2928 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2932 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2935 "event",
2936 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002938 return; // skip the inconsistent event
2939 }
2940
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002941 dispatchEntry->resolvedEventId =
2942 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2943 ? mIdGenerator.nextId()
2944 : motionEntry.id;
2945 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2946 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2947 ") to MotionEvent(id=0x%" PRIx32 ").",
2948 motionEntry.id, dispatchEntry->resolvedEventId);
2949 ATRACE_NAME(message.c_str());
2950 }
2951
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002952 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2953 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2954 // Skip reporting pointer down outside focus to the policy.
2955 break;
2956 }
2957
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002959 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960
2961 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002963 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002964 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2965 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002966 break;
2967 }
Chris Yef59a2f42020-10-16 12:55:26 -07002968 case EventEntry::Type::SENSOR: {
2969 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2970 break;
2971 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002972 case EventEntry::Type::CONFIGURATION_CHANGED:
2973 case EventEntry::Type::DEVICE_RESET: {
2974 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002975 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002976 break;
2977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 }
2979
2980 // Remember that we are waiting for this dispatch to complete.
2981 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002982 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983 }
2984
2985 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002986 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002987 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002988}
2989
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002990/**
2991 * This function is purely for debugging. It helps us understand where the user interaction
2992 * was taking place. For example, if user is touching launcher, we will see a log that user
2993 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2994 * We will see both launcher and wallpaper in that list.
2995 * Once the interaction with a particular set of connections starts, no new logs will be printed
2996 * until the set of interacted connections changes.
2997 *
2998 * The following items are skipped, to reduce the logspam:
2999 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3000 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3001 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3002 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3003 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003004 */
3005void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3006 const std::vector<InputTarget>& targets) {
3007 // Skip ACTION_UP events, and all events other than keys and motions
3008 if (entry.type == EventEntry::Type::KEY) {
3009 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3010 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3011 return;
3012 }
3013 } else if (entry.type == EventEntry::Type::MOTION) {
3014 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3015 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3016 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3017 return;
3018 }
3019 } else {
3020 return; // Not a key or a motion
3021 }
3022
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003023 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003024 std::vector<sp<Connection>> newConnections;
3025 for (const InputTarget& target : targets) {
3026 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3027 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3028 continue; // Skip windows that receive ACTION_OUTSIDE
3029 }
3030
3031 sp<IBinder> token = target.inputChannel->getConnectionToken();
3032 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003033 if (connection == nullptr) {
3034 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003035 }
3036 newConnectionTokens.insert(std::move(token));
3037 newConnections.emplace_back(connection);
3038 }
3039 if (newConnectionTokens == mInteractionConnectionTokens) {
3040 return; // no change
3041 }
3042 mInteractionConnectionTokens = newConnectionTokens;
3043
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003044 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003045 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003046 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003047 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003048 std::string message = "Interaction with: " + targetList;
3049 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003050 message += "<none>";
3051 }
3052 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3053}
3054
chaviwfd6d3512019-03-25 13:23:49 -07003055void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003056 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003057 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003058 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3059 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003060 return;
3061 }
3062
Vishnu Nairc519ff72021-01-21 08:23:08 -08003063 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003064 if (focusedToken == token) {
3065 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003066 return;
3067 }
3068
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003069 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3070 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003071 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003072 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073}
3074
3075void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003077 if (ATRACE_ENABLED()) {
3078 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003080 ATRACE_NAME(message.c_str());
3081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084#endif
3085
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003086 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3087 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003089 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003090 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003091 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092
3093 // Publish the event.
3094 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003095 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3096 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003097 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003098 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3099 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003102 status = connection->inputPublisher
3103 .publishKeyEvent(dispatchEntry->seq,
3104 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3105 keyEntry.source, keyEntry.displayId,
3106 std::move(hmac), dispatchEntry->resolvedAction,
3107 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3108 keyEntry.scanCode, keyEntry.metaState,
3109 keyEntry.repeatCount, keyEntry.downTime,
3110 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 }
3113
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003114 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003115 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003118 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119
chaviw82357092020-01-28 13:13:06 -08003120 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003121 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3123 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003124 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3126 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003127 // Don't apply window scale here since we don't want scale to affect raw
3128 // coordinates. The scale will be sent back to the client and applied
3129 // later when requesting relative coordinates.
3130 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3131 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 }
3133 usingCoords = scaledCoords;
3134 }
3135 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 // We don't want the dispatch target to know.
3137 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003138 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 scaledCoords[i].clear();
3140 }
3141 usingCoords = scaledCoords;
3142 }
3143 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003144
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003145 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146
3147 // Publish the motion event.
3148 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003149 .publishMotionEvent(dispatchEntry->seq,
3150 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003151 motionEntry.deviceId, motionEntry.source,
3152 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003153 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003154 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003156 motionEntry.edgeFlags, motionEntry.metaState,
3157 motionEntry.buttonState,
3158 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003159 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003160 motionEntry.xPrecision, motionEntry.yPrecision,
3161 motionEntry.xCursorPosition,
3162 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003163 dispatchEntry->displaySize.x,
3164 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 motionEntry.downTime, motionEntry.eventTime,
3166 motionEntry.pointerCount,
3167 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 break;
3169 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003170
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003171 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003172 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003173 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003174 focusEntry.id,
3175 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003176 mInTouchMode);
3177 break;
3178 }
3179
Prabir Pradhan99987712020-11-10 18:43:05 -08003180 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3181 const auto& captureEntry =
3182 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3183 status = connection->inputPublisher
3184 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3185 captureEntry.pointerCaptureEnabled);
3186 break;
3187 }
3188
arthurhungb89ccb02020-12-30 16:19:01 +08003189 case EventEntry::Type::DRAG: {
3190 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3191 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3192 dragEntry.id, dragEntry.x,
3193 dragEntry.y,
3194 dragEntry.isExiting);
3195 break;
3196 }
3197
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003198 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003199 case EventEntry::Type::DEVICE_RESET:
3200 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003201 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003202 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206
3207 // Check the result.
3208 if (status) {
3209 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003210 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 "This is unexpected because the wait queue is empty, so the pipe "
3213 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003214 "event to it, status=%s(%d)",
3215 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3216 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3218 } else {
3219 // Pipe is full and we are waiting for the app to finish process some events
3220 // before sending more events to it.
3221#if DEBUG_DISPATCH_CYCLE
3222 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 "waiting for the application to catch up",
3224 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 }
3227 } else {
3228 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003229 "status=%s(%d)",
3230 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3231 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3233 }
3234 return;
3235 }
3236
3237 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003238 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3239 connection->outboundQueue.end(),
3240 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003241 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003242 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003243 if (connection->responsive) {
3244 mAnrTracker.insert(dispatchEntry->timeoutTime,
3245 connection->inputChannel->getConnectionToken());
3246 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003247 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
3249}
3250
chaviw09c8d2d2020-08-24 15:48:26 -07003251std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3252 size_t size;
3253 switch (event.type) {
3254 case VerifiedInputEvent::Type::KEY: {
3255 size = sizeof(VerifiedKeyEvent);
3256 break;
3257 }
3258 case VerifiedInputEvent::Type::MOTION: {
3259 size = sizeof(VerifiedMotionEvent);
3260 break;
3261 }
3262 }
3263 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3264 return mHmacKeyManager.sign(start, size);
3265}
3266
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003267const std::array<uint8_t, 32> InputDispatcher::getSignature(
3268 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3269 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3270 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3271 // Only sign events up and down events as the purely move events
3272 // are tied to their up/down counterparts so signing would be redundant.
3273 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3274 verifiedEvent.actionMasked = actionMasked;
3275 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003276 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003277 }
3278 return INVALID_HMAC;
3279}
3280
3281const std::array<uint8_t, 32> InputDispatcher::getSignature(
3282 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3283 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3284 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3285 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003286 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003287}
3288
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003291 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292#if DEBUG_DISPATCH_CYCLE
3293 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295#endif
3296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 if (connection->status == Connection::STATUS_BROKEN ||
3298 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 return;
3300 }
3301
3302 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003303 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304}
3305
3306void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 const sp<Connection>& connection,
3308 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309#if DEBUG_DISPATCH_CYCLE
3310 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312#endif
3313
3314 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003315 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003316 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003317 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003318 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
3320 // The connection appears to be unrecoverably broken.
3321 // Ignore already broken or zombie connections.
3322 if (connection->status == Connection::STATUS_NORMAL) {
3323 connection->status = Connection::STATUS_BROKEN;
3324
3325 if (notify) {
3326 // Notify other system components.
3327 onDispatchCycleBrokenLocked(currentTime, connection);
3328 }
3329 }
3330}
3331
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003332void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3333 while (!queue.empty()) {
3334 DispatchEntry* dispatchEntry = queue.front();
3335 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003336 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
3338}
3339
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003340void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003342 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
3344 delete dispatchEntry;
3345}
3346
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003347int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3348 std::scoped_lock _l(mLock);
3349 sp<Connection> connection = getConnectionLocked(connectionToken);
3350 if (connection == nullptr) {
3351 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3352 connectionToken.get(), events);
3353 return 0; // remove the callback
3354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003356 bool notify;
3357 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3358 if (!(events & ALOOPER_EVENT_INPUT)) {
3359 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3360 "events=0x%x",
3361 connection->getInputChannelName().c_str(), events);
3362 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 }
3364
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003365 nsecs_t currentTime = now();
3366 bool gotOne = false;
3367 status_t status = OK;
3368 for (;;) {
3369 Result<InputPublisher::ConsumerResponse> result =
3370 connection->inputPublisher.receiveConsumerResponse();
3371 if (!result.ok()) {
3372 status = result.error().code();
3373 break;
3374 }
3375
3376 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3377 const InputPublisher::Finished& finish =
3378 std::get<InputPublisher::Finished>(*result);
3379 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3380 finish.consumeTime);
3381 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003382 if (shouldReportMetricsForConnection(*connection)) {
3383 const InputPublisher::Timeline& timeline =
3384 std::get<InputPublisher::Timeline>(*result);
3385 mLatencyTracker
3386 .trackGraphicsLatency(timeline.inputEventId,
3387 connection->inputChannel->getConnectionToken(),
3388 std::move(timeline.graphicsTimeline));
3389 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003390 }
3391 gotOne = true;
3392 }
3393 if (gotOne) {
3394 runCommandsLockedInterruptible();
3395 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 return 1;
3397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
3399
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003400 notify = status != DEAD_OBJECT || !connection->monitor;
3401 if (notify) {
3402 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3403 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3404 status);
3405 }
3406 } else {
3407 // Monitor channels are never explicitly unregistered.
3408 // We do it automatically when the remote endpoint is closed so don't warn about them.
3409 const bool stillHaveWindowHandle =
3410 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3411 notify = !connection->monitor && stillHaveWindowHandle;
3412 if (notify) {
3413 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3414 connection->getInputChannelName().c_str(), events);
3415 }
3416 }
3417
3418 // Remove the channel.
3419 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3420 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421}
3422
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003425 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003426 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
3428}
3429
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003430void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003431 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003432 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3433 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3434}
3435
3436void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3437 const CancelationOptions& options,
3438 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3439 for (const auto& it : monitorsByDisplay) {
3440 const std::vector<Monitor>& monitors = it.second;
3441 for (const Monitor& monitor : monitors) {
3442 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003443 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003444 }
3445}
3446
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003448 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003449 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003450 if (connection == nullptr) {
3451 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003453
3454 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455}
3456
3457void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3458 const sp<Connection>& connection, const CancelationOptions& options) {
3459 if (connection->status == Connection::STATUS_BROKEN) {
3460 return;
3461 }
3462
3463 nsecs_t currentTime = now();
3464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003465 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003466 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003468 if (cancelationEvents.empty()) {
3469 return;
3470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003472 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3473 "with reality: %s, mode=%d.",
3474 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3475 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003477
3478 InputTarget target;
3479 sp<InputWindowHandle> windowHandle =
3480 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3481 if (windowHandle != nullptr) {
3482 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003483 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003484 target.globalScaleFactor = windowInfo->globalScaleFactor;
3485 }
3486 target.inputChannel = connection->inputChannel;
3487 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3488
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003489 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003490 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003491 switch (cancelationEventEntry->type) {
3492 case EventEntry::Type::KEY: {
3493 logOutboundKeyDetails("cancel - ",
3494 static_cast<const KeyEntry&>(*cancelationEventEntry));
3495 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003497 case EventEntry::Type::MOTION: {
3498 logOutboundMotionDetails("cancel - ",
3499 static_cast<const MotionEntry&>(*cancelationEventEntry));
3500 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003502 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003503 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3504 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003505 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003506 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003507 break;
3508 }
3509 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003510 case EventEntry::Type::DEVICE_RESET:
3511 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003512 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003513 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003514 break;
3515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 }
3517
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003518 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3519 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003521
3522 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523}
3524
Svet Ganov5d3bc372020-01-26 23:11:07 -08003525void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3526 const sp<Connection>& connection) {
3527 if (connection->status == Connection::STATUS_BROKEN) {
3528 return;
3529 }
3530
3531 nsecs_t currentTime = now();
3532
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003533 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003534 connection->inputState.synthesizePointerDownEvents(currentTime);
3535
3536 if (downEvents.empty()) {
3537 return;
3538 }
3539
3540#if DEBUG_OUTBOUND_EVENT_DETAILS
3541 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3542 connection->getInputChannelName().c_str(), downEvents.size());
3543#endif
3544
3545 InputTarget target;
3546 sp<InputWindowHandle> windowHandle =
3547 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3548 if (windowHandle != nullptr) {
3549 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003550 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003551 target.globalScaleFactor = windowInfo->globalScaleFactor;
3552 }
3553 target.inputChannel = connection->inputChannel;
3554 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3555
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003556 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003557 switch (downEventEntry->type) {
3558 case EventEntry::Type::MOTION: {
3559 logOutboundMotionDetails("down - ",
3560 static_cast<const MotionEntry&>(*downEventEntry));
3561 break;
3562 }
3563
3564 case EventEntry::Type::KEY:
3565 case EventEntry::Type::FOCUS:
3566 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003567 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003568 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003569 case EventEntry::Type::SENSOR:
3570 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003571 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003572 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003573 break;
3574 }
3575 }
3576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003577 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3578 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003579 }
3580
3581 startDispatchCycleLocked(currentTime, connection);
3582}
3583
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003584std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3585 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 ALOG_ASSERT(pointerIds.value != 0);
3587
3588 uint32_t splitPointerIndexMap[MAX_POINTERS];
3589 PointerProperties splitPointerProperties[MAX_POINTERS];
3590 PointerCoords splitPointerCoords[MAX_POINTERS];
3591
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003592 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 uint32_t splitPointerCount = 0;
3594
3595 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003596 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003598 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 uint32_t pointerId = uint32_t(pointerProperties.id);
3600 if (pointerIds.hasBit(pointerId)) {
3601 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3602 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3603 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003604 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 splitPointerCount += 1;
3606 }
3607 }
3608
3609 if (splitPointerCount != pointerIds.count()) {
3610 // This is bad. We are missing some of the pointers that we expected to deliver.
3611 // Most likely this indicates that we received an ACTION_MOVE events that has
3612 // different pointer ids than we expected based on the previous ACTION_DOWN
3613 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3614 // in this way.
3615 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003616 "we expected there to be %d pointers. This probably means we received "
3617 "a broken sequence of pointer ids from the input device.",
3618 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003619 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003622 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003624 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3625 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3627 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003628 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 uint32_t pointerId = uint32_t(pointerProperties.id);
3630 if (pointerIds.hasBit(pointerId)) {
3631 if (pointerIds.count() == 1) {
3632 // The first/last pointer went down/up.
3633 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003634 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003635 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3636 ? AMOTION_EVENT_ACTION_CANCEL
3637 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 } else {
3639 // A secondary pointer went down/up.
3640 uint32_t splitPointerIndex = 0;
3641 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3642 splitPointerIndex += 1;
3643 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003644 action = maskedAction |
3645 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647 } else {
3648 // An unrelated pointer changed.
3649 action = AMOTION_EVENT_ACTION_MOVE;
3650 }
3651 }
3652
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003653 int32_t newId = mIdGenerator.nextId();
3654 if (ATRACE_ENABLED()) {
3655 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3656 ") to MotionEvent(id=0x%" PRIx32 ").",
3657 originalMotionEntry.id, newId);
3658 ATRACE_NAME(message.c_str());
3659 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003660 std::unique_ptr<MotionEntry> splitMotionEntry =
3661 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3662 originalMotionEntry.deviceId, originalMotionEntry.source,
3663 originalMotionEntry.displayId,
3664 originalMotionEntry.policyFlags, action,
3665 originalMotionEntry.actionButton,
3666 originalMotionEntry.flags, originalMotionEntry.metaState,
3667 originalMotionEntry.buttonState,
3668 originalMotionEntry.classification,
3669 originalMotionEntry.edgeFlags,
3670 originalMotionEntry.xPrecision,
3671 originalMotionEntry.yPrecision,
3672 originalMotionEntry.xCursorPosition,
3673 originalMotionEntry.yCursorPosition,
3674 originalMotionEntry.downTime, splitPointerCount,
3675 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003677 if (originalMotionEntry.injectionState) {
3678 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 splitMotionEntry->injectionState->refCount += 1;
3680 }
3681
3682 return splitMotionEntry;
3683}
3684
3685void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3686#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003687 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688#endif
3689
3690 bool needWake;
3691 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003692 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003694 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3695 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3696 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 } // release lock
3698
3699 if (needWake) {
3700 mLooper->wake();
3701 }
3702}
3703
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003704/**
3705 * If one of the meta shortcuts is detected, process them here:
3706 * Meta + Backspace -> generate BACK
3707 * Meta + Enter -> generate HOME
3708 * This will potentially overwrite keyCode and metaState.
3709 */
3710void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003711 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003712 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3713 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3714 if (keyCode == AKEYCODE_DEL) {
3715 newKeyCode = AKEYCODE_BACK;
3716 } else if (keyCode == AKEYCODE_ENTER) {
3717 newKeyCode = AKEYCODE_HOME;
3718 }
3719 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003720 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003721 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003722 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003723 keyCode = newKeyCode;
3724 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3725 }
3726 } else if (action == AKEY_EVENT_ACTION_UP) {
3727 // In order to maintain a consistent stream of up and down events, check to see if the key
3728 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3729 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003730 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003731 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003732 auto replacementIt = mReplacedKeys.find(replacement);
3733 if (replacementIt != mReplacedKeys.end()) {
3734 keyCode = replacementIt->second;
3735 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003736 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3737 }
3738 }
3739}
3740
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3742#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003743 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3744 "policyFlags=0x%x, action=0x%x, "
3745 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3746 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3747 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3748 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749#endif
3750 if (!validateKeyEvent(args->action)) {
3751 return;
3752 }
3753
3754 uint32_t policyFlags = args->policyFlags;
3755 int32_t flags = args->flags;
3756 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003757 // InputDispatcher tracks and generates key repeats on behalf of
3758 // whatever notifies it, so repeatCount should always be set to 0
3759 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3761 policyFlags |= POLICY_FLAG_VIRTUAL;
3762 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 if (policyFlags & POLICY_FLAG_FUNCTION) {
3765 metaState |= AMETA_FUNCTION_ON;
3766 }
3767
3768 policyFlags |= POLICY_FLAG_TRUSTED;
3769
Michael Wright78f24442014-08-06 15:55:28 -07003770 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003771 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003772
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003774 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003775 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3776 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
Michael Wright2b3c3302018-03-02 17:19:13 +00003778 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003780 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3781 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003782 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 bool needWake;
3786 { // acquire lock
3787 mLock.lock();
3788
3789 if (shouldSendKeyToInputFilterLocked(args)) {
3790 mLock.unlock();
3791
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003792 policyFlags |= POLICY_FLAG_FILTERED | POLICY_FLAG_INPUTFILTER_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3794 return; // event was consumed by the filter
3795 }
3796
3797 mLock.lock();
3798 }
3799
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003800 std::unique_ptr<KeyEntry> newEntry =
3801 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3802 args->displayId, policyFlags, args->action, flags,
3803 keyCode, args->scanCode, metaState, repeatCount,
3804 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003806 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 mLock.unlock();
3808 } // release lock
3809
3810 if (needWake) {
3811 mLooper->wake();
3812 }
3813}
3814
3815bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3816 return mInputFilterEnabled;
3817}
3818
3819void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3820#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003821 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3822 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003823 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3824 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003825 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003826 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3827 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3828 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3829 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 for (uint32_t i = 0; i < args->pointerCount; i++) {
3831 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 "x=%f, y=%f, pressure=%f, size=%f, "
3833 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3834 "orientation=%f",
3835 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3836 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3837 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3838 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3839 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3840 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3841 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3842 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3843 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3844 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 }
3846#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003847 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3848 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 return;
3850 }
3851
3852 uint32_t policyFlags = args->policyFlags;
3853 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003854
3855 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003856 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003857 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3858 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003859 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861
3862 bool needWake;
3863 { // acquire lock
3864 mLock.lock();
3865
3866 if (shouldSendMotionToInputFilterLocked(args)) {
3867 mLock.unlock();
3868
3869 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003870 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003871 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3872 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003873 args->metaState, args->buttonState, args->classification, transform,
3874 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003875 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3876 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003877 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
3879 policyFlags |= POLICY_FLAG_FILTERED;
3880 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3881 return; // event was consumed by the filter
3882 }
3883
3884 mLock.lock();
3885 }
3886
3887 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003888 std::unique_ptr<MotionEntry> newEntry =
3889 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3890 args->source, args->displayId, policyFlags,
3891 args->action, args->actionButton, args->flags,
3892 args->metaState, args->buttonState,
3893 args->classification, args->edgeFlags,
3894 args->xPrecision, args->yPrecision,
3895 args->xCursorPosition, args->yCursorPosition,
3896 args->downTime, args->pointerCount,
3897 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003899 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 mLock.unlock();
3901 } // release lock
3902
3903 if (needWake) {
3904 mLooper->wake();
3905 }
3906}
3907
Chris Yef59a2f42020-10-16 12:55:26 -07003908void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3909#if DEBUG_INBOUND_EVENT_DETAILS
3910 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3911 " sensorType=%s",
3912 args->id, args->eventTime, args->deviceId, args->source,
3913 NamedEnum::string(args->sensorType).c_str());
3914#endif
3915
3916 bool needWake;
3917 { // acquire lock
3918 mLock.lock();
3919
3920 // Just enqueue a new sensor event.
3921 std::unique_ptr<SensorEntry> newEntry =
3922 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3923 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3924 args->sensorType, args->accuracy,
3925 args->accuracyChanged, args->values);
3926
3927 needWake = enqueueInboundEventLocked(std::move(newEntry));
3928 mLock.unlock();
3929 } // release lock
3930
3931 if (needWake) {
3932 mLooper->wake();
3933 }
3934}
3935
Chris Yefb552902021-02-03 17:18:37 -08003936void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3937#if DEBUG_INBOUND_EVENT_DETAILS
3938 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3939 args->deviceId, args->isOn);
3940#endif
3941 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3942}
3943
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003945 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946}
3947
3948void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3949#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003950 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003951 "switchMask=0x%08x",
3952 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953#endif
3954
3955 uint32_t policyFlags = args->policyFlags;
3956 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003957 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958}
3959
3960void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3961#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3963 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964#endif
3965
3966 bool needWake;
3967 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003968 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003970 std::unique_ptr<DeviceResetEntry> newEntry =
3971 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3972 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 } // release lock
3974
3975 if (needWake) {
3976 mLooper->wake();
3977 }
3978}
3979
Prabir Pradhan7e186182020-11-10 13:56:45 -08003980void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3981#if DEBUG_INBOUND_EVENT_DETAILS
3982 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3983 args->enabled ? "true" : "false");
3984#endif
3985
Prabir Pradhan99987712020-11-10 18:43:05 -08003986 bool needWake;
3987 { // acquire lock
3988 std::scoped_lock _l(mLock);
3989 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3990 args->enabled);
3991 needWake = enqueueInboundEventLocked(std::move(entry));
3992 } // release lock
3993
3994 if (needWake) {
3995 mLooper->wake();
3996 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003997}
3998
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003999InputEventInjectionResult InputDispatcher::injectInputEvent(
4000 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4001 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002#if DEBUG_INBOUND_EVENT_DETAILS
4003 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004004 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4005 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004007 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008
4009 policyFlags |= POLICY_FLAG_INJECTED;
4010 if (hasInjectionPermission(injectorPid, injectorUid)) {
4011 policyFlags |= POLICY_FLAG_TRUSTED;
4012 }
4013
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004014 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
4015 // that have gone through the InputFilter. If the event passed through the InputFilter,
4016 // but did not get modified, assign the provided device id. If the InputFilter modifies the
4017 // events in any way, it is responsible for removing this flag.
4018 // If the injected event originated from accessibility, assign the accessibility device id,
4019 // so that it can be distinguished from regular injected events.
4020 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
4021 if (policyFlags & POLICY_FLAG_INPUTFILTER_TRUSTED) {
4022 resolvedDeviceId = event->getDeviceId();
4023 } else if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4024 resolvedDeviceId = ACCESSIBILITY_DEVICE_ID;
4025 }
4026
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004027 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004029 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004030 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4031 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004032 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004033 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004036 int32_t flags = incomingKey.getFlags();
4037 int32_t keyCode = incomingKey.getKeyCode();
4038 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004039 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004041 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004042 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004043 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4044 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4045 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4048 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004049 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004050
4051 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4052 android::base::Timer t;
4053 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4054 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4055 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4056 std::to_string(t.duration().count()).c_str());
4057 }
4058 }
4059
4060 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004061 std::unique_ptr<KeyEntry> injectedEntry =
4062 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004063 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004064 incomingKey.getDisplayId(), policyFlags, action,
4065 flags, keyCode, incomingKey.getScanCode(), metaState,
4066 incomingKey.getRepeatCount(),
4067 incomingKey.getDownTime());
4068 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004069 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 }
4071
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004072 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004073 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4074 int32_t action = motionEvent.getAction();
4075 size_t pointerCount = motionEvent.getPointerCount();
4076 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4077 int32_t actionButton = motionEvent.getActionButton();
4078 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004080 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 }
4082
4083 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004084 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 android::base::Timer t;
4086 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4087 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4088 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4089 std::to_string(t.duration().count()).c_str());
4090 }
4091 }
4092
4093 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004094 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4095 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004096 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004097 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4098 resolvedDeviceId, motionEvent.getSource(),
4099 motionEvent.getDisplayId(), policyFlags, action,
4100 actionButton, motionEvent.getFlags(),
4101 motionEvent.getMetaState(),
4102 motionEvent.getButtonState(),
4103 motionEvent.getClassification(),
4104 motionEvent.getEdgeFlags(),
4105 motionEvent.getXPrecision(),
4106 motionEvent.getYPrecision(),
4107 motionEvent.getRawXCursorPosition(),
4108 motionEvent.getRawYCursorPosition(),
4109 motionEvent.getDownTime(), uint32_t(pointerCount),
4110 pointerProperties, samplePointerCoords,
4111 motionEvent.getXOffset(),
4112 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004113 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004114 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 sampleEventTimes += 1;
4116 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004117 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004118 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4119 resolvedDeviceId, motionEvent.getSource(),
4120 motionEvent.getDisplayId(), policyFlags,
4121 action, actionButton, motionEvent.getFlags(),
4122 motionEvent.getMetaState(),
4123 motionEvent.getButtonState(),
4124 motionEvent.getClassification(),
4125 motionEvent.getEdgeFlags(),
4126 motionEvent.getXPrecision(),
4127 motionEvent.getYPrecision(),
4128 motionEvent.getRawXCursorPosition(),
4129 motionEvent.getRawYCursorPosition(),
4130 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004131 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004132 samplePointerCoords, motionEvent.getXOffset(),
4133 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004134 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004135 }
4136 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004139 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004140 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004141 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143
4144 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004145 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 injectionState->injectionIsAsync = true;
4147 }
4148
4149 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004150 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151
4152 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004153 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004154 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004155 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156 }
4157
4158 mLock.unlock();
4159
4160 if (needWake) {
4161 mLooper->wake();
4162 }
4163
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004164 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004166 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004168 if (syncMode == InputEventInjectionSync::NONE) {
4169 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 } else {
4171 for (;;) {
4172 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 break;
4175 }
4176
4177 nsecs_t remainingTimeout = endTime - now();
4178 if (remainingTimeout <= 0) {
4179#if DEBUG_INJECTION
4180 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004183 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 break;
4185 }
4186
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004187 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 }
4189
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004190 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4191 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 while (injectionState->pendingForegroundDispatches != 0) {
4193#if DEBUG_INJECTION
4194 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196#endif
4197 nsecs_t remainingTimeout = endTime - now();
4198 if (remainingTimeout <= 0) {
4199#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4201 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004203 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 break;
4205 }
4206
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004207 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
4209 }
4210 }
4211
4212 injectionState->release();
4213 } // release lock
4214
4215#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004216 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218#endif
4219
4220 return injectionResult;
4221}
4222
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004223std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004224 std::array<uint8_t, 32> calculatedHmac;
4225 std::unique_ptr<VerifiedInputEvent> result;
4226 switch (event.getType()) {
4227 case AINPUT_EVENT_TYPE_KEY: {
4228 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4229 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4230 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004231 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004232 break;
4233 }
4234 case AINPUT_EVENT_TYPE_MOTION: {
4235 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4236 VerifiedMotionEvent verifiedMotionEvent =
4237 verifiedMotionEventFromMotionEvent(motionEvent);
4238 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004239 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004240 break;
4241 }
4242 default: {
4243 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4244 return nullptr;
4245 }
4246 }
4247 if (calculatedHmac == INVALID_HMAC) {
4248 return nullptr;
4249 }
4250 if (calculatedHmac != event.getHmac()) {
4251 return nullptr;
4252 }
4253 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004254}
4255
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 return injectorUid == 0 ||
4258 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259}
4260
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004261void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004262 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 if (injectionState) {
4265#if DEBUG_INJECTION
4266 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 "injectorPid=%d, injectorUid=%d",
4268 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269#endif
4270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 // Log the outcome since the injector did not wait for the injection result.
4273 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004274 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004275 ALOGV("Asynchronous input event injection succeeded.");
4276 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004277 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 ALOGW("Asynchronous input event injection failed.");
4279 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004280 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 ALOGW("Asynchronous input event injection permission denied.");
4282 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004283 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 ALOGW("Asynchronous input event injection timed out.");
4285 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004286 case InputEventInjectionResult::PENDING:
4287 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4288 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 }
4290 }
4291
4292 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004293 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295}
4296
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004297void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4298 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 if (injectionState) {
4300 injectionState->pendingForegroundDispatches += 1;
4301 }
4302}
4303
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004304void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4305 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 if (injectionState) {
4307 injectionState->pendingForegroundDispatches -= 1;
4308
4309 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004310 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312 }
4313}
4314
Vishnu Nairad321cd2020-08-20 16:40:21 -07004315const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004316 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004317 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4318 auto it = mWindowHandlesByDisplay.find(displayId);
4319 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004320}
4321
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004323 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004324 if (windowHandleToken == nullptr) {
4325 return nullptr;
4326 }
4327
Arthur Hungb92218b2018-08-14 12:00:21 +08004328 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004329 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004330 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004331 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004332 return windowHandle;
4333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
4335 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004336 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337}
4338
Vishnu Nairad321cd2020-08-20 16:40:21 -07004339sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4340 int displayId) const {
4341 if (windowHandleToken == nullptr) {
4342 return nullptr;
4343 }
4344
4345 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4346 if (windowHandle->getToken() == windowHandleToken) {
4347 return windowHandle;
4348 }
4349 }
4350 return nullptr;
4351}
4352
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004353sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4354 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004355 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004356 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004357 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004358 if (handle->getId() == windowHandle->getId() &&
4359 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004360 if (windowHandle->getInfo()->displayId != it.first) {
4361 ALOGE("Found window %s in display %" PRId32
4362 ", but it should belong to display %" PRId32,
4363 windowHandle->getName().c_str(), it.first,
4364 windowHandle->getInfo()->displayId);
4365 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004366 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004370 return nullptr;
4371}
4372
4373sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4374 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4375 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376}
4377
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004378bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4379 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4380 const bool noInputChannel =
4381 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4382 if (connection != nullptr && noInputChannel) {
4383 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4384 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4385 return false;
4386 }
4387
4388 if (connection == nullptr) {
4389 if (!noInputChannel) {
4390 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4391 }
4392 return false;
4393 }
4394 if (!connection->responsive) {
4395 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4396 return false;
4397 }
4398 return true;
4399}
4400
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004401std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4402 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004403 auto connectionIt = mConnectionsByToken.find(token);
4404 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004405 return nullptr;
4406 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004407 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004408}
4409
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004410void InputDispatcher::updateWindowHandlesForDisplayLocked(
4411 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4412 if (inputWindowHandles.empty()) {
4413 // Remove all handles on a display if there are no windows left.
4414 mWindowHandlesByDisplay.erase(displayId);
4415 return;
4416 }
4417
4418 // Since we compare the pointer of input window handles across window updates, we need
4419 // to make sure the handle object for the same window stays unchanged across updates.
4420 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004421 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004422 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004423 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004424 }
4425
4426 std::vector<sp<InputWindowHandle>> newHandles;
4427 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4428 if (!handle->updateInfo()) {
4429 // handle no longer valid
4430 continue;
4431 }
4432
4433 const InputWindowInfo* info = handle->getInfo();
4434 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4435 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4436 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004437 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4438 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4439 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004440 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004441 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004442 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004443 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004444 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004445 }
4446
4447 if (info->displayId != displayId) {
4448 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4449 handle->getName().c_str(), displayId, info->displayId);
4450 continue;
4451 }
4452
Robert Carredd13602020-04-13 17:24:34 -07004453 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4454 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004455 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004456 oldHandle->updateFrom(handle);
4457 newHandles.push_back(oldHandle);
4458 } else {
4459 newHandles.push_back(handle);
4460 }
4461 }
4462
4463 // Insert or replace
4464 mWindowHandlesByDisplay[displayId] = newHandles;
4465}
4466
Arthur Hung72d8dc32020-03-28 00:48:39 +00004467void InputDispatcher::setInputWindows(
4468 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4469 { // acquire lock
4470 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004471 for (const auto& [displayId, handles] : handlesPerDisplay) {
4472 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004473 }
4474 }
4475 // Wake up poll loop since it may need to make new input dispatching choices.
4476 mLooper->wake();
4477}
4478
Arthur Hungb92218b2018-08-14 12:00:21 +08004479/**
4480 * Called from InputManagerService, update window handle list by displayId that can receive input.
4481 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4482 * If set an empty list, remove all handles from the specific display.
4483 * For focused handle, check if need to change and send a cancel event to previous one.
4484 * For removed handle, check if need to send a cancel event if already in touch.
4485 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004486void InputDispatcher::setInputWindowsLocked(
4487 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004488 if (DEBUG_FOCUS) {
4489 std::string windowList;
4490 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4491 windowList += iwh->getName() + " ";
4492 }
4493 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004496 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4497 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4498 const bool noInputWindow =
4499 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4500 if (noInputWindow && window->getToken() != nullptr) {
4501 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4502 window->getName().c_str());
4503 window->releaseChannel();
4504 }
4505 }
4506
Arthur Hung72d8dc32020-03-28 00:48:39 +00004507 // Copy old handles for release if they are no longer present.
4508 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004510 // Save the old windows' orientation by ID before it gets updated.
4511 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4512 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4513 oldWindowOrientations.emplace(handle->getId(),
4514 handle->getInfo()->transform.getOrientation());
4515 }
4516
Arthur Hung72d8dc32020-03-28 00:48:39 +00004517 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004518
Vishnu Nair958da932020-08-21 17:12:37 -07004519 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4520 if (mLastHoverWindowHandle &&
4521 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4522 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004523 mLastHoverWindowHandle = nullptr;
4524 }
4525
Vishnu Nairc519ff72021-01-21 08:23:08 -08004526 std::optional<FocusResolver::FocusChanges> changes =
4527 mFocusResolver.setInputWindows(displayId, windowHandles);
4528 if (changes) {
4529 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004532 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4533 mTouchStatesByDisplay.find(displayId);
4534 if (stateIt != mTouchStatesByDisplay.end()) {
4535 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004536 for (size_t i = 0; i < state.windows.size();) {
4537 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004538 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004539 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004540 ALOGD("Touched window was removed: %s in display %" PRId32,
4541 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004542 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004543 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004544 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4545 if (touchedInputChannel != nullptr) {
4546 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4547 "touched window was removed");
4548 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004550 state.windows.erase(state.windows.begin() + i);
4551 } else {
4552 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 }
4554 }
arthurhungb89ccb02020-12-30 16:19:01 +08004555
arthurhung6d4bed92021-03-17 11:59:33 +08004556 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004557 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004558 if (mDragState &&
4559 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004560 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004561 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004562 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004563 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004564
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004565 if (isPerWindowInputRotationEnabled()) {
4566 // Determine if the orientation of any of the input windows have changed, and cancel all
4567 // pointer events if necessary.
4568 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4569 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4570 if (newWindowHandle != nullptr &&
4571 newWindowHandle->getInfo()->transform.getOrientation() !=
4572 oldWindowOrientations[oldWindowHandle->getId()]) {
4573 std::shared_ptr<InputChannel> inputChannel =
4574 getInputChannelLocked(newWindowHandle->getToken());
4575 if (inputChannel != nullptr) {
4576 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4577 "touched window's orientation changed");
4578 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4579 }
4580 }
4581 }
4582 }
4583
Arthur Hung72d8dc32020-03-28 00:48:39 +00004584 // Release information for windows that are no longer present.
4585 // This ensures that unused input channels are released promptly.
4586 // Otherwise, they might stick around until the window handle is destroyed
4587 // which might not happen until the next GC.
4588 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004589 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004590 if (DEBUG_FOCUS) {
4591 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004592 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004593 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004594 // To avoid making too many calls into the compat framework, only
4595 // check for window flags when windows are going away.
4596 // TODO(b/157929241) : delete this. This is only needed temporarily
4597 // in order to gather some data about the flag usage
4598 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4599 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4600 oldWindowHandle->getName().c_str());
4601 if (mCompatService != nullptr) {
4602 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4603 oldWindowHandle->getInfo()->ownerUid);
4604 }
4605 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004606 }
chaviw291d88a2019-02-14 10:33:58 -08004607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608}
4609
4610void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004611 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004612 if (DEBUG_FOCUS) {
4613 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4614 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4615 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004616 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004617 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618
Chris Yea209fde2020-07-22 13:54:51 -07004619 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004620 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004622 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4623 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004624 }
4625
Chris Yea209fde2020-07-22 13:54:51 -07004626 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004627 if (inputApplicationHandle != nullptr) {
4628 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4629 } else {
4630 mFocusedApplicationHandlesByDisplay.erase(displayId);
4631 }
4632
4633 // No matter what the old focused application was, stop waiting on it because it is
4634 // no longer focused.
4635 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 } // release lock
4637
4638 // Wake up poll loop since it may need to make new input dispatching choices.
4639 mLooper->wake();
4640}
4641
Tiger Huang721e26f2018-07-24 22:26:19 +08004642/**
4643 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4644 * the display not specified.
4645 *
4646 * We track any unreleased events for each window. If a window loses the ability to receive the
4647 * released event, we will send a cancel event to it. So when the focused display is changed, we
4648 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4649 * display. The display-specified events won't be affected.
4650 */
4651void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004652 if (DEBUG_FOCUS) {
4653 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4654 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004655 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004656 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004657
4658 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004659 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004660 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004661 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004662 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004663 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004664 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004665 CancelationOptions
4666 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4667 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004668 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004669 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4670 }
4671 }
4672 mFocusedDisplayId = displayId;
4673
Chris Ye3c2d6f52020-08-09 10:39:48 -07004674 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004675 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004676 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004677
Vishnu Nairad321cd2020-08-20 16:40:21 -07004678 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004679 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004680 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004681 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004682 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004683 }
4684 }
4685 }
4686
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004687 if (DEBUG_FOCUS) {
4688 logDispatchStateLocked();
4689 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004690 } // release lock
4691
4692 // Wake up poll loop since it may need to make new input dispatching choices.
4693 mLooper->wake();
4694}
4695
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004697 if (DEBUG_FOCUS) {
4698 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700
4701 bool changed;
4702 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004703 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704
4705 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4706 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004707 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 }
4709
4710 if (mDispatchEnabled && !enabled) {
4711 resetAndDropEverythingLocked("dispatcher is being disabled");
4712 }
4713
4714 mDispatchEnabled = enabled;
4715 mDispatchFrozen = frozen;
4716 changed = true;
4717 } else {
4718 changed = false;
4719 }
4720
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004721 if (DEBUG_FOCUS) {
4722 logDispatchStateLocked();
4723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 } // release lock
4725
4726 if (changed) {
4727 // Wake up poll loop since it may need to make new input dispatching choices.
4728 mLooper->wake();
4729 }
4730}
4731
4732void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004733 if (DEBUG_FOCUS) {
4734 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
4737 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004738 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739
4740 if (mInputFilterEnabled == enabled) {
4741 return;
4742 }
4743
4744 mInputFilterEnabled = enabled;
4745 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4746 } // release lock
4747
4748 // Wake up poll loop since there might be work to do to drop everything.
4749 mLooper->wake();
4750}
4751
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004752void InputDispatcher::setInTouchMode(bool inTouchMode) {
4753 std::scoped_lock lock(mLock);
4754 mInTouchMode = inTouchMode;
4755}
4756
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004757void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4758 if (opacity < 0 || opacity > 1) {
4759 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4760 return;
4761 }
4762
4763 std::scoped_lock lock(mLock);
4764 mMaximumObscuringOpacityForTouch = opacity;
4765}
4766
4767void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4768 std::scoped_lock lock(mLock);
4769 mBlockUntrustedTouchesMode = mode;
4770}
4771
arthurhungb89ccb02020-12-30 16:19:01 +08004772bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4773 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004774 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004775 if (DEBUG_FOCUS) {
4776 ALOGD("Trivial transfer to same window.");
4777 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004778 return true;
4779 }
4780
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004782 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783
chaviwfbe5d9c2018-12-26 12:23:37 -08004784 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4785 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004786 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004787 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 return false;
4789 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004790 if (DEBUG_FOCUS) {
4791 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4792 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004795 if (DEBUG_FOCUS) {
4796 ALOGD("Cannot transfer focus because windows are on different displays.");
4797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 return false;
4799 }
4800
4801 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004802 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4803 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004804 for (size_t i = 0; i < state.windows.size(); i++) {
4805 const TouchedWindow& touchedWindow = state.windows[i];
4806 if (touchedWindow.windowHandle == fromWindowHandle) {
4807 int32_t oldTargetFlags = touchedWindow.targetFlags;
4808 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004810 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 int32_t newTargetFlags = oldTargetFlags &
4813 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4814 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004815 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
arthurhungb89ccb02020-12-30 16:19:01 +08004817 // Store the dragging window.
4818 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004819 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004820 }
4821
Jeff Brownf086ddb2014-02-11 14:28:48 -08004822 found = true;
4823 goto Found;
4824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 }
4826 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004829 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004830 if (DEBUG_FOCUS) {
4831 ALOGD("Focus transfer failed because from window did not have focus.");
4832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 return false;
4834 }
4835
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004836 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4837 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004838 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004839 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004840 CancelationOptions
4841 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4842 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004844 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004847 if (DEBUG_FOCUS) {
4848 logDispatchStateLocked();
4849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 } // release lock
4851
4852 // Wake up poll loop since it may need to make new input dispatching choices.
4853 mLooper->wake();
4854 return true;
4855}
4856
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004857// Binder call
4858bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4859 sp<IBinder> fromToken;
4860 { // acquire lock
4861 std::scoped_lock _l(mLock);
4862
4863 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4864 if (toWindowHandle == nullptr) {
4865 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4866 return false;
4867 }
4868
4869 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4870
4871 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4872 if (touchStateIt == mTouchStatesByDisplay.end()) {
4873 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4874 displayId);
4875 return false;
4876 }
4877
4878 TouchState& state = touchStateIt->second;
4879 if (state.windows.size() != 1) {
4880 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4881 state.windows.size());
4882 return false;
4883 }
4884 const TouchedWindow& touchedWindow = state.windows[0];
4885 fromToken = touchedWindow.windowHandle->getToken();
4886 } // release lock
4887
4888 return transferTouchFocus(fromToken, destChannelToken);
4889}
4890
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004892 if (DEBUG_FOCUS) {
4893 ALOGD("Resetting and dropping all events (%s).", reason);
4894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895
4896 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4897 synthesizeCancelationEventsForAllConnectionsLocked(options);
4898
4899 resetKeyRepeatLocked();
4900 releasePendingEventLocked();
4901 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004905 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004907 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908}
4909
4910void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004911 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 dumpDispatchStateLocked(dump);
4913
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004914 std::istringstream stream(dump);
4915 std::string line;
4916
4917 while (std::getline(stream, line, '\n')) {
4918 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 }
4920}
4921
Prabir Pradhan99987712020-11-10 18:43:05 -08004922std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4923 std::string dump;
4924
4925 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4926 toString(mFocusedWindowRequestedPointerCapture));
4927
4928 std::string windowName = "None";
4929 if (mWindowTokenWithPointerCapture) {
4930 const sp<InputWindowHandle> captureWindowHandle =
4931 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4932 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4933 : "token has capture without window";
4934 }
4935 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4936
4937 return dump;
4938}
4939
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004940void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004941 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4942 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4943 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004944 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945
Tiger Huang721e26f2018-07-24 22:26:19 +08004946 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4947 dump += StringPrintf(INDENT "FocusedApplications:\n");
4948 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4949 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004950 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004951 const std::chrono::duration timeout =
4952 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004953 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004954 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004955 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004958 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004960
Vishnu Nairc519ff72021-01-21 08:23:08 -08004961 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004962 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004964 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004965 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004966 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4967 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004968 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004969 state.displayId, toString(state.down), toString(state.split),
4970 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004971 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004972 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004973 for (size_t i = 0; i < state.windows.size(); i++) {
4974 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004975 dump += StringPrintf(INDENT4
4976 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4977 i, touchedWindow.windowHandle->getName().c_str(),
4978 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004979 }
4980 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004981 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004982 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004983 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004984 dump += INDENT3 "Portal windows:\n";
4985 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004986 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004987 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4988 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004989 }
4990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991 }
4992 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004993 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 }
4995
arthurhung6d4bed92021-03-17 11:59:33 +08004996 if (mDragState) {
4997 dump += StringPrintf(INDENT "DragState:\n");
4998 mDragState->dump(dump, INDENT2);
4999 }
5000
Arthur Hungb92218b2018-08-14 12:00:21 +08005001 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005002 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005003 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005004 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005005 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005006 dump += INDENT2 "Windows:\n";
5007 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005008 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08005009 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005011 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005012 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005013 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005014 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005015 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005016 "applicationInfo.name=%s, "
5017 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005018 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005019 i, windowInfo->name.c_str(), windowInfo->id,
5020 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005021 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005022 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005023 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005024 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005025 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005026 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005027 windowInfo->frameLeft, windowInfo->frameTop,
5028 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005029 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005030 windowInfo->applicationInfo.name.c_str(),
5031 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005032 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005033 dump += StringPrintf(", inputFeatures=%s",
5034 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005035 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005036 "ms, trustedOverlay=%s, hasToken=%s, "
5037 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005038 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005039 millis(windowInfo->dispatchingTimeout),
5040 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005041 toString(windowInfo->token != nullptr),
5042 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005043 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005044 }
5045 } else {
5046 dump += INDENT2 "Windows: <none>\n";
5047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 }
5049 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005050 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 }
5052
Michael Wright3dd60e22019-03-27 22:06:44 +00005053 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005054 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005055 const std::vector<Monitor>& monitors = it.second;
5056 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5057 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 }
5059 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005060 const std::vector<Monitor>& monitors = it.second;
5061 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5062 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005065 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 }
5067
5068 nsecs_t currentTime = now();
5069
5070 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005071 if (!mRecentQueue.empty()) {
5072 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005073 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005074 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005075 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005076 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077 }
5078 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005079 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 }
5081
5082 // Dump event currently being dispatched.
5083 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005084 dump += INDENT "PendingEvent:\n";
5085 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005086 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005087 dump += StringPrintf(", age=%" PRId64 "ms\n",
5088 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005090 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 }
5092
5093 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005094 if (!mInboundQueue.empty()) {
5095 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005096 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005097 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005098 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005099 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005102 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 }
5104
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005105 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005107 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5108 const KeyReplacement& replacement = pair.first;
5109 int32_t newKeyCode = pair.second;
5110 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005111 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005112 }
5113 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005114 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005115 }
5116
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005117 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005118 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005119 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005120 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005121 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005122 connection->inputChannel->getFd().get(),
5123 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005124 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005125 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005127 if (!connection->outboundQueue.empty()) {
5128 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5129 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005130 dump += dumpQueue(connection->outboundQueue, currentTime);
5131
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005133 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 }
5135
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005136 if (!connection->waitQueue.empty()) {
5137 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5138 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005139 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005141 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 }
5143 }
5144 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005145 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
5147
5148 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005149 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5150 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005152 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 }
5154
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005155 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005156 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5157 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5158 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005159 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005160 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161}
5162
Michael Wright3dd60e22019-03-27 22:06:44 +00005163void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5164 const size_t numMonitors = monitors.size();
5165 for (size_t i = 0; i < numMonitors; i++) {
5166 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005167 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005168 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5169 dump += "\n";
5170 }
5171}
5172
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005173class LooperEventCallback : public LooperCallback {
5174public:
5175 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5176 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5177
5178private:
5179 std::function<int(int events)> mCallback;
5180};
5181
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005182Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005183#if DEBUG_CHANNEL_CREATION
5184 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185#endif
5186
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005187 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005188 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005189 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005190
5191 if (result) {
5192 return base::Error(result) << "Failed to open input channel pair with name " << name;
5193 }
5194
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005196 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005197 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005198 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005199 sp<Connection> connection =
5200 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005202 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5203 ALOGE("Created a new connection, but the token %p is already known", token.get());
5204 }
5205 mConnectionsByToken.emplace(token, connection);
5206
5207 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5208 this, std::placeholders::_1, token);
5209
5210 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211 } // release lock
5212
5213 // Wake the looper because some connections have changed.
5214 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005215 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216}
5217
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005218Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5219 bool isGestureMonitor,
5220 const std::string& name,
5221 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005222 std::shared_ptr<InputChannel> serverChannel;
5223 std::unique_ptr<InputChannel> clientChannel;
5224 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5225 if (result) {
5226 return base::Error(result) << "Failed to open input channel pair with name " << name;
5227 }
5228
Michael Wright3dd60e22019-03-27 22:06:44 +00005229 { // acquire lock
5230 std::scoped_lock _l(mLock);
5231
5232 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005233 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5234 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005235 }
5236
Garfield Tan15601662020-09-22 15:32:38 -07005237 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005238 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005239 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005240
5241 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5242 ALOGE("Created a new connection, but the token %p is already known", token.get());
5243 }
5244 mConnectionsByToken.emplace(token, connection);
5245 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5246 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005247
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005248 auto& monitorsByDisplay =
5249 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005250 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005251
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005252 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005253 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5254 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005255 }
Garfield Tan15601662020-09-22 15:32:38 -07005256
Michael Wright3dd60e22019-03-27 22:06:44 +00005257 // Wake the looper because some connections have changed.
5258 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005259 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005260}
5261
Garfield Tan15601662020-09-22 15:32:38 -07005262status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005264 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265
Garfield Tan15601662020-09-22 15:32:38 -07005266 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 if (status) {
5268 return status;
5269 }
5270 } // release lock
5271
5272 // Wake the poll loop because removing the connection may have changed the current
5273 // synchronization state.
5274 mLooper->wake();
5275 return OK;
5276}
5277
Garfield Tan15601662020-09-22 15:32:38 -07005278status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5279 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005280 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005281 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005282 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 return BAD_VALUE;
5284 }
5285
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005286 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005287
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005289 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 }
5291
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005292 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293
5294 nsecs_t currentTime = now();
5295 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5296
5297 connection->status = Connection::STATUS_ZOMBIE;
5298 return OK;
5299}
5300
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005301void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5302 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5303 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005304}
5305
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005306void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005307 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005308 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005309 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005310 std::vector<Monitor>& monitors = it->second;
5311 const size_t numMonitors = monitors.size();
5312 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005313 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005314 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5315 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005316 monitors.erase(monitors.begin() + i);
5317 break;
5318 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005319 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005320 if (monitors.empty()) {
5321 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005322 } else {
5323 ++it;
5324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 }
5326}
5327
Michael Wright3dd60e22019-03-27 22:06:44 +00005328status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5329 { // acquire lock
5330 std::scoped_lock _l(mLock);
5331 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5332
5333 if (!foundDisplayId) {
5334 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5335 return BAD_VALUE;
5336 }
5337 int32_t displayId = foundDisplayId.value();
5338
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005339 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5340 mTouchStatesByDisplay.find(displayId);
5341 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005342 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5343 return BAD_VALUE;
5344 }
5345
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005346 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005347 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005348 std::optional<int32_t> foundDeviceId;
5349 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005350 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005351 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005352 foundDeviceId = state.deviceId;
5353 }
5354 }
5355 if (!foundDeviceId || !state.down) {
5356 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005357 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005358 return BAD_VALUE;
5359 }
5360 int32_t deviceId = foundDeviceId.value();
5361
5362 // Send cancel events to all the input channels we're stealing from.
5363 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005364 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005365 options.deviceId = deviceId;
5366 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005367 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005368 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005369 std::shared_ptr<InputChannel> channel =
5370 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005371 if (channel != nullptr) {
5372 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005373 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005374 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005375 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005376 canceledWindows += "]";
5377 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5378 canceledWindows.c_str());
5379
Michael Wright3dd60e22019-03-27 22:06:44 +00005380 // Then clear the current touch state so we stop dispatching to them as well.
5381 state.filterNonMonitors();
5382 }
5383 return OK;
5384}
5385
Prabir Pradhan99987712020-11-10 18:43:05 -08005386void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5387 { // acquire lock
5388 std::scoped_lock _l(mLock);
5389 if (DEBUG_FOCUS) {
5390 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5391 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5392 windowHandle != nullptr ? windowHandle->getName().c_str()
5393 : "token without window");
5394 }
5395
Vishnu Nairc519ff72021-01-21 08:23:08 -08005396 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005397 if (focusedToken != windowToken) {
5398 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5399 enabled ? "enable" : "disable");
5400 return;
5401 }
5402
5403 if (enabled == mFocusedWindowRequestedPointerCapture) {
5404 ALOGW("Ignoring request to %s Pointer Capture: "
5405 "window has %s requested pointer capture.",
5406 enabled ? "enable" : "disable", enabled ? "already" : "not");
5407 return;
5408 }
5409
5410 mFocusedWindowRequestedPointerCapture = enabled;
5411 setPointerCaptureLocked(enabled);
5412 } // release lock
5413
5414 // Wake the thread to process command entries.
5415 mLooper->wake();
5416}
5417
Michael Wright3dd60e22019-03-27 22:06:44 +00005418std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5419 const sp<IBinder>& token) {
5420 for (const auto& it : mGestureMonitorsByDisplay) {
5421 const std::vector<Monitor>& monitors = it.second;
5422 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005423 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005424 return it.first;
5425 }
5426 }
5427 }
5428 return std::nullopt;
5429}
5430
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005431std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5432 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5433 if (gesturePid.has_value()) {
5434 return gesturePid;
5435 }
5436 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5437}
5438
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005439sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005440 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005441 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005442 }
5443
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005444 for (const auto& [token, connection] : mConnectionsByToken) {
5445 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005446 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 }
5448 }
Robert Carr4e670e52018-08-15 13:26:12 -07005449
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005450 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451}
5452
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005453std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5454 sp<Connection> connection = getConnectionLocked(connectionToken);
5455 if (connection == nullptr) {
5456 return "<nullptr>";
5457 }
5458 return connection->getInputChannelName();
5459}
5460
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005461void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005462 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005463 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005464}
5465
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005466void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5467 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005468 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005469 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5470 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 commandEntry->connection = connection;
5472 commandEntry->eventTime = currentTime;
5473 commandEntry->seq = seq;
5474 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005475 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005476 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477}
5478
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005479void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5480 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005482 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005484 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5485 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005487 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488}
5489
Vishnu Nairad321cd2020-08-20 16:40:21 -07005490void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5491 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005492 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5493 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005494 commandEntry->oldToken = oldToken;
5495 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005496 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005497}
5498
arthurhungf452d0b2021-01-06 00:19:52 +08005499void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5500 std::unique_ptr<CommandEntry> commandEntry =
5501 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5502 commandEntry->newToken = token;
5503 commandEntry->x = x;
5504 commandEntry->y = y;
5505 postCommandLocked(std::move(commandEntry));
5506}
5507
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005508void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5509 if (connection == nullptr) {
5510 LOG_ALWAYS_FATAL("Caller must check for nullness");
5511 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005512 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5513 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005514 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005515 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005516 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005517 return;
5518 }
5519 /**
5520 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5521 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5522 * has changed. This could cause newer entries to time out before the already dispatched
5523 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5524 * processes the events linearly. So providing information about the oldest entry seems to be
5525 * most useful.
5526 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005527 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005528 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5529 std::string reason =
5530 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005531 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005532 ns2ms(currentWait),
5533 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005534 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005535 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005536
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005537 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5538
5539 // Stop waking up for events on this connection, it is already unresponsive
5540 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005541}
5542
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005543void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5544 std::string reason =
5545 StringPrintf("%s does not have a focused window", application->getName().c_str());
5546 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005547
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005548 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5549 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5550 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005551 postCommandLocked(std::move(commandEntry));
5552}
5553
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005554void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5555 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5556 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5557 commandEntry->obscuringPackage = obscuringPackage;
5558 postCommandLocked(std::move(commandEntry));
5559}
5560
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005561void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5562 const std::string& reason) {
5563 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5564 updateLastAnrStateLocked(windowLabel, reason);
5565}
5566
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005567void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5568 const std::string& reason) {
5569 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005570 updateLastAnrStateLocked(windowLabel, reason);
5571}
5572
5573void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5574 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005576 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577 struct tm tm;
5578 localtime_r(&t, &tm);
5579 char timestr[64];
5580 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005581 mLastAnrState.clear();
5582 mLastAnrState += INDENT "ANR:\n";
5583 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005584 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5585 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005586 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587}
5588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005589void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 mLock.unlock();
5591
5592 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5593
5594 mLock.lock();
5595}
5596
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005597void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 sp<Connection> connection = commandEntry->connection;
5599
5600 if (connection->status != Connection::STATUS_ZOMBIE) {
5601 mLock.unlock();
5602
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005603 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604
5605 mLock.lock();
5606 }
5607}
5608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005609void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005610 sp<IBinder> oldToken = commandEntry->oldToken;
5611 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005612 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005613 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005614 mLock.lock();
5615}
5616
arthurhungf452d0b2021-01-06 00:19:52 +08005617void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5618 sp<IBinder> newToken = commandEntry->newToken;
5619 mLock.unlock();
5620 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5621 mLock.lock();
5622}
5623
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005624void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005626
5627 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5628
5629 mLock.lock();
5630}
5631
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005632void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005633 mLock.unlock();
5634
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005635 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636
5637 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005638}
5639
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005640void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005641 mLock.unlock();
5642
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005643 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5644
5645 mLock.lock();
5646}
5647
5648void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5649 mLock.unlock();
5650
5651 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5652
5653 mLock.lock();
5654}
5655
5656void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5657 mLock.unlock();
5658
5659 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005660
5661 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005662}
5663
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005664void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5665 mLock.unlock();
5666
5667 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5668
5669 mLock.lock();
5670}
5671
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5673 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005674 KeyEntry& entry = *(commandEntry->keyEntry);
5675 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676
5677 mLock.unlock();
5678
Michael Wright2b3c3302018-03-02 17:19:13 +00005679 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005680 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005681 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005682 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5683 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005684 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686
5687 mLock.lock();
5688
5689 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005690 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005692 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005694 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5695 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005697}
5698
chaviwfd6d3512019-03-25 13:23:49 -07005699void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5700 mLock.unlock();
5701 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5702 mLock.lock();
5703}
5704
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005705/**
5706 * Connection is responsive if it has no events in the waitQueue that are older than the
5707 * current time.
5708 */
5709static bool isConnectionResponsive(const Connection& connection) {
5710 const nsecs_t currentTime = now();
5711 for (const DispatchEntry* entry : connection.waitQueue) {
5712 if (entry->timeoutTime < currentTime) {
5713 return false;
5714 }
5715 }
5716 return true;
5717}
5718
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005719void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005721 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005723 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724
5725 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005726 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005727 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005728 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005730 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005731 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005732 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005733 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5734 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005735 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005736 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5737 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5738 connection->inputChannel->getConnectionToken(),
5739 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5740 finishTime);
5741 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005742
5743 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005744 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005745 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005746 restartEvent =
5747 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005748 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005749 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005750 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5751 handled);
5752 } else {
5753 restartEvent = false;
5754 }
5755
5756 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005757 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005758 // contents of the wait queue to have been drained, so we need to double-check
5759 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005760 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5761 if (dispatchEntryIt != connection->waitQueue.end()) {
5762 dispatchEntry = *dispatchEntryIt;
5763 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005764 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5765 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005766 if (!connection->responsive) {
5767 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005768 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005769 // The connection was unresponsive, and now it's responsive.
5770 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005771 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005772 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005773 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005774 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005775 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005776 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005777 } else {
5778 releaseDispatchEntry(dispatchEntry);
5779 }
5780 }
5781
5782 // Start the next dispatch cycle for this connection.
5783 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784}
5785
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005786void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5787 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5788 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5789 monitorUnresponsiveCommand->pid = pid;
5790 monitorUnresponsiveCommand->reason = std::move(reason);
5791 postCommandLocked(std::move(monitorUnresponsiveCommand));
5792}
5793
5794void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5795 std::string reason) {
5796 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5797 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5798 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5799 windowUnresponsiveCommand->reason = std::move(reason);
5800 postCommandLocked(std::move(windowUnresponsiveCommand));
5801}
5802
5803void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5804 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5805 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5806 monitorResponsiveCommand->pid = pid;
5807 postCommandLocked(std::move(monitorResponsiveCommand));
5808}
5809
5810void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5811 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5812 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5813 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5814 postCommandLocked(std::move(windowResponsiveCommand));
5815}
5816
5817/**
5818 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5819 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5820 * command entry to the command queue.
5821 */
5822void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5823 std::string reason) {
5824 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5825 if (connection.monitor) {
5826 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5827 reason.c_str());
5828 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5829 if (!pid.has_value()) {
5830 ALOGE("Could not find unresponsive monitor for connection %s",
5831 connection.inputChannel->getName().c_str());
5832 return;
5833 }
5834 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5835 return;
5836 }
5837 // If not a monitor, must be a window
5838 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5839 reason.c_str());
5840 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5841}
5842
5843/**
5844 * Tell the policy that a connection has become responsive so that it can stop ANR.
5845 */
5846void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5847 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5848 if (connection.monitor) {
5849 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5850 if (!pid.has_value()) {
5851 ALOGE("Could not find responsive monitor for connection %s",
5852 connection.inputChannel->getName().c_str());
5853 return;
5854 }
5855 sendMonitorResponsiveCommandLocked(pid.value());
5856 return;
5857 }
5858 // If not a monitor, must be a window
5859 sendWindowResponsiveCommandLocked(connectionToken);
5860}
5861
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005863 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005864 KeyEntry& keyEntry, bool handled) {
5865 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005866 if (!handled) {
5867 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005868 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005869 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005870 return false;
5871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005873 // Get the fallback key state.
5874 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005875 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005876 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005877 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005878 connection->inputState.removeFallbackKey(originalKeyCode);
5879 }
5880
5881 if (handled || !dispatchEntry->hasForegroundTarget()) {
5882 // If the application handles the original key for which we previously
5883 // generated a fallback or if the window is not a foreground window,
5884 // then cancel the associated fallback key, if any.
5885 if (fallbackKeyCode != -1) {
5886 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005888 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005889 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005890 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005892 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005893 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894
5895 mLock.unlock();
5896
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005897 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005898 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005899
5900 mLock.lock();
5901
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005902 // Cancel the fallback key.
5903 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005905 "application handled the original non-fallback key "
5906 "or is no longer a foreground target, "
5907 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 options.keyCode = fallbackKeyCode;
5909 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005911 connection->inputState.removeFallbackKey(originalKeyCode);
5912 }
5913 } else {
5914 // If the application did not handle a non-fallback key, first check
5915 // that we are in a good state to perform unhandled key event processing
5916 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005917 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005918 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005920 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005921 "since this is not an initial down. "
5922 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005923 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005925 return false;
5926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005928 // Dispatch the unhandled key to the policy.
5929#if DEBUG_OUTBOUND_EVENT_DETAILS
5930 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005931 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005933#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005934 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005935
5936 mLock.unlock();
5937
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005938 bool fallback =
5939 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005940 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005941
5942 mLock.lock();
5943
5944 if (connection->status != Connection::STATUS_NORMAL) {
5945 connection->inputState.removeFallbackKey(originalKeyCode);
5946 return false;
5947 }
5948
5949 // Latch the fallback keycode for this key on an initial down.
5950 // The fallback keycode cannot change at any other point in the lifecycle.
5951 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005953 fallbackKeyCode = event.getKeyCode();
5954 } else {
5955 fallbackKeyCode = AKEYCODE_UNKNOWN;
5956 }
5957 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5958 }
5959
5960 ALOG_ASSERT(fallbackKeyCode != -1);
5961
5962 // Cancel the fallback key if the policy decides not to send it anymore.
5963 // We will continue to dispatch the key to the policy but we will no
5964 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005965 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5966 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005967#if DEBUG_OUTBOUND_EVENT_DETAILS
5968 if (fallback) {
5969 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005970 "as a fallback for %d, but on the DOWN it had requested "
5971 "to send %d instead. Fallback canceled.",
5972 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973 } else {
5974 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005975 "but on the DOWN it had requested to send %d. "
5976 "Fallback canceled.",
5977 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005978 }
5979#endif
5980
5981 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5982 "canceling fallback, policy no longer desires it");
5983 options.keyCode = fallbackKeyCode;
5984 synthesizeCancelationEventsForConnectionLocked(connection, options);
5985
5986 fallback = false;
5987 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005988 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005989 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005990 }
5991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992
5993#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005994 {
5995 std::string msg;
5996 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5997 connection->inputState.getFallbackKeys();
5998 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005999 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006001 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006002 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006003 }
6004#endif
6005
6006 if (fallback) {
6007 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006008 keyEntry.eventTime = event.getEventTime();
6009 keyEntry.deviceId = event.getDeviceId();
6010 keyEntry.source = event.getSource();
6011 keyEntry.displayId = event.getDisplayId();
6012 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6013 keyEntry.keyCode = fallbackKeyCode;
6014 keyEntry.scanCode = event.getScanCode();
6015 keyEntry.metaState = event.getMetaState();
6016 keyEntry.repeatCount = event.getRepeatCount();
6017 keyEntry.downTime = event.getDownTime();
6018 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006019
6020#if DEBUG_OUTBOUND_EVENT_DETAILS
6021 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006022 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006023 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006024#endif
6025 return true; // restart the event
6026 } else {
6027#if DEBUG_OUTBOUND_EVENT_DETAILS
6028 ALOGD("Unhandled key event: No fallback key.");
6029#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006030
6031 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006032 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033 }
6034 }
6035 return false;
6036}
6037
6038bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006039 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006040 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041 return false;
6042}
6043
6044void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6045 mLock.unlock();
6046
Sean Stoutb4e0a592021-02-23 07:34:53 -08006047 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6048 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049
6050 mLock.lock();
6051}
6052
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053void InputDispatcher::traceInboundQueueLengthLocked() {
6054 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006055 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056 }
6057}
6058
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006059void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 if (ATRACE_ENABLED()) {
6061 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006062 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6063 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064 }
6065}
6066
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006067void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 if (ATRACE_ENABLED()) {
6069 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006070 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6071 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072 }
6073}
6074
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006075void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006076 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006077
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006078 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 dumpDispatchStateLocked(dump);
6080
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006081 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006082 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006083 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084 }
6085}
6086
6087void InputDispatcher::monitor() {
6088 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006089 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006091 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092}
6093
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006094/**
6095 * Wake up the dispatcher and wait until it processes all events and commands.
6096 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6097 * this method can be safely called from any thread, as long as you've ensured that
6098 * the work you are interested in completing has already been queued.
6099 */
6100bool InputDispatcher::waitForIdle() {
6101 /**
6102 * Timeout should represent the longest possible time that a device might spend processing
6103 * events and commands.
6104 */
6105 constexpr std::chrono::duration TIMEOUT = 100ms;
6106 std::unique_lock lock(mLock);
6107 mLooper->wake();
6108 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6109 return result == std::cv_status::no_timeout;
6110}
6111
Vishnu Naire798b472020-07-23 13:52:21 -07006112/**
6113 * Sets focus to the window identified by the token. This must be called
6114 * after updating any input window handles.
6115 *
6116 * Params:
6117 * request.token - input channel token used to identify the window that should gain focus.
6118 * request.focusedToken - the token that the caller expects currently to be focused. If the
6119 * specified token does not match the currently focused window, this request will be dropped.
6120 * If the specified focused token matches the currently focused window, the call will succeed.
6121 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6122 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6123 * when requesting the focus change. This determines which request gets
6124 * precedence if there is a focus change request from another source such as pointer down.
6125 */
Vishnu Nair958da932020-08-21 17:12:37 -07006126void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6127 { // acquire lock
6128 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006129 std::optional<FocusResolver::FocusChanges> changes =
6130 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6131 if (changes) {
6132 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006133 }
6134 } // release lock
6135 // Wake up poll loop since it may need to make new input dispatching choices.
6136 mLooper->wake();
6137}
6138
Vishnu Nairc519ff72021-01-21 08:23:08 -08006139void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6140 if (changes.oldFocus) {
6141 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006142 if (focusedInputChannel) {
6143 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6144 "focus left window");
6145 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006146 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006147 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006148 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006149 if (changes.newFocus) {
6150 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006151 }
6152
Prabir Pradhan99987712020-11-10 18:43:05 -08006153 // If a window has pointer capture, then it must have focus. We need to ensure that this
6154 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6155 // If the window loses focus before it loses pointer capture, then the window can be in a state
6156 // where it has pointer capture but not focus, violating the contract. Therefore we must
6157 // dispatch the pointer capture event before the focus event. Since focus events are added to
6158 // the front of the queue (above), we add the pointer capture event to the front of the queue
6159 // after the focus events are added. This ensures the pointer capture event ends up at the
6160 // front.
6161 disablePointerCaptureForcedLocked();
6162
Vishnu Nairc519ff72021-01-21 08:23:08 -08006163 if (mFocusedDisplayId == changes.displayId) {
6164 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006165 }
6166}
Vishnu Nair958da932020-08-21 17:12:37 -07006167
Prabir Pradhan99987712020-11-10 18:43:05 -08006168void InputDispatcher::disablePointerCaptureForcedLocked() {
6169 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6170 return;
6171 }
6172
6173 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6174
6175 if (mFocusedWindowRequestedPointerCapture) {
6176 mFocusedWindowRequestedPointerCapture = false;
6177 setPointerCaptureLocked(false);
6178 }
6179
6180 if (!mWindowTokenWithPointerCapture) {
6181 // No need to send capture changes because no window has capture.
6182 return;
6183 }
6184
6185 if (mPendingEvent != nullptr) {
6186 // Move the pending event to the front of the queue. This will give the chance
6187 // for the pending event to be dropped if it is a captured event.
6188 mInboundQueue.push_front(mPendingEvent);
6189 mPendingEvent = nullptr;
6190 }
6191
6192 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6193 false /* hasCapture */);
6194 mInboundQueue.push_front(std::move(entry));
6195}
6196
Prabir Pradhan99987712020-11-10 18:43:05 -08006197void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6198 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6199 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6200 commandEntry->enabled = enabled;
6201 postCommandLocked(std::move(commandEntry));
6202}
6203
6204void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6205 android::inputdispatcher::CommandEntry* commandEntry) {
6206 mLock.unlock();
6207
6208 mPolicy->setPointerCapture(commandEntry->enabled);
6209
6210 mLock.lock();
6211}
6212
Garfield Tane84e6f92019-08-29 17:28:41 -07006213} // namespace android::inputdispatcher