blob: 15c810db5f6c2fb91dc63e0857ae219cc48363cf [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
liushenxiang42232912021-05-21 20:24:09 +08001261 // Reset key repeating in case a keyboard device was disabled or enabled.
1262 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1263 resetKeyRepeatLocked();
1264 }
1265
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001266 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 synthesizeCancelationEventsForAllConnectionsLocked(options);
1269 return true;
1270}
1271
Vishnu Nairad321cd2020-08-20 16:40:21 -07001272void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001273 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001274 if (mPendingEvent != nullptr) {
1275 // Move the pending event to the front of the queue. This will give the chance
1276 // for the pending event to get dispatched to the newly focused window
1277 mInboundQueue.push_front(mPendingEvent);
1278 mPendingEvent = nullptr;
1279 }
1280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 std::unique_ptr<FocusEntry> focusEntry =
1282 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1283 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001284
1285 // This event should go to the front of the queue, but behind all other focus events
1286 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001288 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289 [](const std::shared_ptr<EventEntry>& event) {
1290 return event->type == EventEntry::Type::FOCUS;
1291 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001292
1293 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001295}
1296
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001297void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001298 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001299 if (channel == nullptr) {
1300 return; // Window has gone away
1301 }
1302 InputTarget target;
1303 target.inputChannel = channel;
1304 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1305 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001306 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1307 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001308 std::string reason = std::string("reason=").append(entry->reason);
1309 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001310 dispatchEventLocked(currentTime, entry, {target});
1311}
1312
Prabir Pradhan99987712020-11-10 18:43:05 -08001313void InputDispatcher::dispatchPointerCaptureChangedLocked(
1314 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1315 DropReason& dropReason) {
1316 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001317 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1318 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1319 }
1320 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001321 // Pointer capture was already forcefully disabled because of focus change.
1322 dropReason = DropReason::NOT_DROPPED;
1323 return;
1324 }
1325
1326 // Set drop reason for early returns
1327 dropReason = DropReason::NO_POINTER_CAPTURE;
1328
1329 sp<IBinder> token;
1330 if (entry->pointerCaptureEnabled) {
1331 // Enable Pointer Capture
1332 if (!mFocusedWindowRequestedPointerCapture) {
1333 // This can happen if a window requests capture and immediately releases capture.
1334 ALOGW("No window requested Pointer Capture.");
1335 return;
1336 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001337 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001338 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1339 mWindowTokenWithPointerCapture = token;
1340 } else {
1341 // Disable Pointer Capture
1342 token = mWindowTokenWithPointerCapture;
1343 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001344 if (mFocusedWindowRequestedPointerCapture) {
1345 mFocusedWindowRequestedPointerCapture = false;
1346 setPointerCaptureLocked(false);
1347 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001348 }
1349
1350 auto channel = getInputChannelLocked(token);
1351 if (channel == nullptr) {
1352 // Window has gone away, clean up Pointer Capture state.
1353 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001354 if (mFocusedWindowRequestedPointerCapture) {
1355 mFocusedWindowRequestedPointerCapture = false;
1356 setPointerCaptureLocked(false);
1357 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001358 return;
1359 }
1360 InputTarget target;
1361 target.inputChannel = channel;
1362 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1363 entry->dispatchInProgress = true;
1364 dispatchEventLocked(currentTime, entry, {target});
1365
1366 dropReason = DropReason::NOT_DROPPED;
1367}
1368
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001369bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001372 if (!entry->dispatchInProgress) {
1373 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1374 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1375 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1376 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001377 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 // We have seen two identical key downs in a row which indicates that the device
1379 // driver is automatically generating key repeats itself. We take note of the
1380 // repeat here, but we disable our own next key repeat timer since it is clear that
1381 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001382 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1383 // Make sure we don't get key down from a different device. If a different
1384 // device Id has same key pressed down, the new device Id will replace the
1385 // current one to hold the key repeat with repeat count reset.
1386 // In the future when got a KEY_UP on the device id, drop it and do not
1387 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1389 resetKeyRepeatLocked();
1390 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1391 } else {
1392 // Not a repeat. Save key down state in case we do see a repeat later.
1393 resetKeyRepeatLocked();
1394 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1395 }
1396 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001397 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1398 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001399 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001400#if DEBUG_INBOUND_EVENT_DETAILS
1401 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1402#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001403 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 resetKeyRepeatLocked();
1405 }
1406
1407 if (entry->repeatCount == 1) {
1408 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1409 } else {
1410 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1411 }
1412
1413 entry->dispatchInProgress = true;
1414
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001415 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 }
1417
1418 // Handle case where the policy asked us to try again later last time.
1419 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1420 if (currentTime < entry->interceptKeyWakeupTime) {
1421 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1422 *nextWakeupTime = entry->interceptKeyWakeupTime;
1423 }
1424 return false; // wait until next wakeup
1425 }
1426 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1427 entry->interceptKeyWakeupTime = 0;
1428 }
1429
1430 // Give the policy a chance to intercept the key.
1431 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1432 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001433 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001434 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001435 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001436 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001437 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001439 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 return false; // wait for the command to run
1441 } else {
1442 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1443 }
1444 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001445 if (*dropReason == DropReason::NOT_DROPPED) {
1446 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 }
1448 }
1449
1450 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001451 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001453 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1454 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001455 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 return true;
1457 }
1458
1459 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001460 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001462 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001463 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 return false;
1465 }
1466
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001467 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001468 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 return true;
1470 }
1471
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001472 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001473 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474
1475 // Dispatch the key.
1476 dispatchEventLocked(currentTime, entry, inputTargets);
1477 return true;
1478}
1479
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001482 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1484 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1486 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1487 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488#endif
1489}
1490
Chris Yef59a2f42020-10-16 12:55:26 -07001491void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1492 mLock.unlock();
1493
1494 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1495 if (entry->accuracyChanged) {
1496 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1497 }
1498 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1499 entry->hwTimestamp, entry->values);
1500 mLock.lock();
1501}
1502
1503void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1504 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1505#if DEBUG_OUTBOUND_EVENT_DETAILS
1506 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1507 "source=0x%x, sensorType=%s",
1508 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001509 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001510#endif
1511 std::unique_ptr<CommandEntry> commandEntry =
1512 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1513 commandEntry->sensorEntry = entry;
1514 postCommandLocked(std::move(commandEntry));
1515}
1516
1517bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1518#if DEBUG_OUTBOUND_EVENT_DETAILS
1519 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1520 NamedEnum::string(sensorType).c_str());
1521#endif
1522 { // acquire lock
1523 std::scoped_lock _l(mLock);
1524
1525 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1526 std::shared_ptr<EventEntry> entry = *it;
1527 if (entry->type == EventEntry::Type::SENSOR) {
1528 it = mInboundQueue.erase(it);
1529 releaseInboundEventLocked(entry);
1530 }
1531 }
1532 }
1533 return true;
1534}
1535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001536bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001537 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001538 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001540 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 entry->dispatchInProgress = true;
1542
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001543 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
1546 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001547 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001549 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1550 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 return true;
1552 }
1553
1554 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1555
1556 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001557 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558
1559 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 if (isPointerEvent) {
1562 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001564 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001565 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 } else {
1567 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001569 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 return false;
1573 }
1574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001577 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1578 return true;
1579 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001580 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001581 CancelationOptions::Mode mode(isPointerEvent
1582 ? CancelationOptions::CANCEL_POINTER_EVENTS
1583 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1584 CancelationOptions options(mode, "input event injection failed");
1585 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 return true;
1587 }
1588
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001589 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001590 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001592 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001593 std::unordered_map<int32_t, TouchState>::iterator it =
1594 mTouchStatesByDisplay.find(entry->displayId);
1595 if (it != mTouchStatesByDisplay.end()) {
1596 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001597 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001598 // The event has gone through these portal windows, so we add monitoring targets of
1599 // the corresponding displays as well.
1600 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001601 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001602 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001603 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001604 }
1605 }
1606 }
1607 }
1608
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 // Dispatch the motion.
1610 if (conflictingPointerActions) {
1611 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 synthesizeCancelationEventsForAllConnectionsLocked(options);
1614 }
1615 dispatchEventLocked(currentTime, entry, inputTargets);
1616 return true;
1617}
1618
arthurhungb89ccb02020-12-30 16:19:01 +08001619void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1620 bool isExiting, const MotionEntry& motionEntry) {
1621 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1622 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1623 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1624 PointerCoords pointerCoords;
1625 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1626 pointerCoords.transform(windowHandle->getInfo()->transform);
1627
1628 std::unique_ptr<DragEntry> dragEntry =
1629 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1630 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1631 pointerCoords.getY());
1632
1633 enqueueInboundEventLocked(std::move(dragEntry));
1634}
1635
1636void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1637 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1638 if (channel == nullptr) {
1639 return; // Window has gone away
1640 }
1641 InputTarget target;
1642 target.inputChannel = channel;
1643 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1644 entry->dispatchInProgress = true;
1645 dispatchEventLocked(currentTime, entry, {target});
1646}
1647
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001650 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001651 ", policyFlags=0x%x, "
1652 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1653 "metaState=0x%x, buttonState=0x%x,"
1654 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001655 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1656 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1657 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001659 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 "x=%f, y=%f, pressure=%f, size=%f, "
1662 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1663 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001664 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1665 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1666 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1667 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1668 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1669 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1670 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1671 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1672 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1673 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 }
1675#endif
1676}
1677
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001678void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1679 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001681 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682#if DEBUG_DISPATCH_CYCLE
1683 ALOGD("dispatchEventToCurrentInputTargets");
1684#endif
1685
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001686 updateInteractionTokensLocked(*eventEntry, inputTargets);
1687
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1689
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001690 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001692 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001693 sp<Connection> connection =
1694 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001695 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001696 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001698 if (DEBUG_FOCUS) {
1699 ALOGD("Dropping event delivery to target with channel '%s' because it "
1700 "is no longer registered with the input dispatcher.",
1701 inputTarget.inputChannel->getName().c_str());
1702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 }
1704 }
1705}
1706
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001707void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1708 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1709 // If the policy decides to close the app, we will get a channel removal event via
1710 // unregisterInputChannel, and will clean up the connection that way. We are already not
1711 // sending new pointers to the connection when it blocked, but focused events will continue to
1712 // pile up.
1713 ALOGW("Canceling events for %s because it is unresponsive",
1714 connection->inputChannel->getName().c_str());
1715 if (connection->status == Connection::STATUS_NORMAL) {
1716 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1717 "application not responding");
1718 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 }
1720}
1721
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001722void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001723 if (DEBUG_FOCUS) {
1724 ALOGD("Resetting ANR timeouts.");
1725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726
1727 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001728 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001729 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730}
1731
Tiger Huang721e26f2018-07-24 22:26:19 +08001732/**
1733 * Get the display id that the given event should go to. If this event specifies a valid display id,
1734 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1735 * Focused display is the display that the user most recently interacted with.
1736 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001738 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001739 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001740 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001741 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1742 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001743 break;
1744 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001745 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001746 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1747 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 break;
1749 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001750 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001751 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001752 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001753 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001754 case EventEntry::Type::SENSOR:
1755 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001756 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001757 return ADISPLAY_ID_NONE;
1758 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001759 }
1760 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1761}
1762
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001763bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1764 const char* focusedWindowName) {
1765 if (mAnrTracker.empty()) {
1766 // already processed all events that we waited for
1767 mKeyIsWaitingForEventsTimeout = std::nullopt;
1768 return false;
1769 }
1770
1771 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1772 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001773 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001774 mKeyIsWaitingForEventsTimeout = currentTime +
1775 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1776 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001777 return true;
1778 }
1779
1780 // We still have pending events, and already started the timer
1781 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1782 return true; // Still waiting
1783 }
1784
1785 // Waited too long, and some connection still hasn't processed all motions
1786 // Just send the key to the focused window
1787 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1788 focusedWindowName);
1789 mKeyIsWaitingForEventsTimeout = std::nullopt;
1790 return false;
1791}
1792
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1794 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1795 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001796 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797
Tiger Huang721e26f2018-07-24 22:26:19 +08001798 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001799 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001800 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001801 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1802
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 // If there is no currently focused window and no focused application
1804 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001805 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1806 ALOGI("Dropping %s event because there is no focused window or focused application in "
1807 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001808 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001809 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 }
1811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001812 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1813 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1814 // start interacting with another application via touch (app switch). This code can be removed
1815 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1816 // an app is expected to have a focused window.
1817 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1818 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1819 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001820 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1821 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1822 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001824 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001825 ALOGW("Waiting because no window has focus but %s may eventually add a "
1826 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001827 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001828 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001829 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001830 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1831 // Already raised ANR. Drop the event
1832 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001833 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001834 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001835 } else {
1836 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001838 }
1839 }
1840
1841 // we have a valid, non-null focused window
1842 resetNoFocusedWindowTimeoutLocked();
1843
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001845 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001846 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 }
1848
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 if (focusedWindowHandle->getInfo()->paused) {
1850 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001852 }
1853
1854 // If the event is a key event, then we must wait for all previous events to
1855 // complete before delivering it because previous events may have the
1856 // side-effect of transferring focus to a different window and we want to
1857 // ensure that the following keys are sent to the new window.
1858 //
1859 // Suppose the user touches a button in a window then immediately presses "A".
1860 // If the button causes a pop-up window to appear then we want to ensure that
1861 // the "A" key is delivered to the new pop-up window. This is because users
1862 // often anticipate pending UI changes when typing on a keyboard.
1863 // To obtain this behavior, we must serialize key events with respect to all
1864 // prior input events.
1865 if (entry.type == EventEntry::Type::KEY) {
1866 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1867 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001868 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
1871
1872 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001873 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001874 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1875 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876
1877 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879}
1880
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001881/**
1882 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1883 * that are currently unresponsive.
1884 */
1885std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1886 const std::vector<TouchedMonitor>& monitors) const {
1887 std::vector<TouchedMonitor> responsiveMonitors;
1888 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1889 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1890 sp<Connection> connection = getConnectionLocked(
1891 monitor.monitor.inputChannel->getConnectionToken());
1892 if (connection == nullptr) {
1893 ALOGE("Could not find connection for monitor %s",
1894 monitor.monitor.inputChannel->getName().c_str());
1895 return false;
1896 }
1897 if (!connection->responsive) {
1898 ALOGW("Unresponsive monitor %s will not get the new gesture",
1899 connection->inputChannel->getName().c_str());
1900 return false;
1901 }
1902 return true;
1903 });
1904 return responsiveMonitors;
1905}
1906
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1908 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1909 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001910 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 enum InjectionPermission {
1912 INJECTION_PERMISSION_UNKNOWN,
1913 INJECTION_PERMISSION_GRANTED,
1914 INJECTION_PERMISSION_DENIED
1915 };
1916
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 // For security reasons, we defer updating the touch state until we are sure that
1918 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001919 int32_t displayId = entry.displayId;
1920 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1922
1923 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001924 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001926 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1927 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001929 // Copy current touch state into tempTouchState.
1930 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1931 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001932 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001933 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001934 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1935 mTouchStatesByDisplay.find(displayId);
1936 if (oldStateIt != mTouchStatesByDisplay.end()) {
1937 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001938 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001939 }
1940
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001941 bool isSplit = tempTouchState.split;
1942 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1943 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1944 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001945 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1946 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1947 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1948 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1949 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001950 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 bool wrongDevice = false;
1952 if (newGesture) {
1953 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001954 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001955 ALOGI("Dropping event because a pointer for a different device is already down "
1956 "in display %" PRId32,
1957 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001958 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 switchedDevice = false;
1961 wrongDevice = true;
1962 goto Failed;
1963 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001964 tempTouchState.reset();
1965 tempTouchState.down = down;
1966 tempTouchState.deviceId = entry.deviceId;
1967 tempTouchState.source = entry.source;
1968 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001970 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001971 ALOGI("Dropping move event because a pointer for a different device is already active "
1972 "in display %" PRId32,
1973 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001974 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001975 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001976 switchedDevice = false;
1977 wrongDevice = true;
1978 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 }
1980
1981 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1982 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1983
Garfield Tan00f511d2019-06-12 16:55:40 -07001984 int32_t x;
1985 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001987 // Always dispatch mouse events to cursor position.
1988 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001989 x = int32_t(entry.xCursorPosition);
1990 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001991 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001992 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1993 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001994 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001995 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001996 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1998 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001999
2000 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002001 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00002002 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002005 if (newTouchedWindowHandle != nullptr &&
2006 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002007 // New window supports splitting, but we should never split mouse events.
2008 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 } else if (isSplit) {
2010 // New window does not support splitting but we have already split events.
2011 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002012 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 }
2014
2015 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002016 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002018 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002019 }
2020
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2022 ALOGI("Not sending touch event to %s because it is paused",
2023 newTouchedWindowHandle->getName().c_str());
2024 newTouchedWindowHandle = nullptr;
2025 }
2026
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002027 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002029 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2030 if (!isResponsive) {
2031 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002032 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2033 newTouchedWindowHandle = nullptr;
2034 }
2035 }
2036
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002037 // Drop events that can't be trusted due to occlusion
2038 if (newTouchedWindowHandle != nullptr &&
2039 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2040 TouchOcclusionInfo occlusionInfo =
2041 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002042 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002043 if (DEBUG_TOUCH_OCCLUSION) {
2044 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2045 for (const auto& log : occlusionInfo.debugInfo) {
2046 ALOGD("%s", log.c_str());
2047 }
2048 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002049 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2050 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2051 ALOGW("Dropping untrusted touch event due to %s/%d",
2052 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2053 newTouchedWindowHandle = nullptr;
2054 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002055 }
2056 }
2057
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002058 // Also don't send the new touch event to unresponsive gesture monitors
2059 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2060
Michael Wright3dd60e22019-03-27 22:06:44 +00002061 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2062 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 "(%d, %d) in display %" PRId32 ".",
2064 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002065 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002066 goto Failed;
2067 }
2068
2069 if (newTouchedWindowHandle != nullptr) {
2070 // Set target flags.
2071 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2072 if (isSplit) {
2073 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002075 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2076 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2077 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2078 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2079 }
2080
2081 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002082 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2083 newHoverWindowHandle = nullptr;
2084 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002086 }
2087
2088 // Update the temporary touch state.
2089 BitSet32 pointerIds;
2090 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002091 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002092 pointerIds.markBit(pointerId);
2093 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002094 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 }
2096
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002097 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 } else {
2099 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2100
2101 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002102 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002103 if (DEBUG_FOCUS) {
2104 ALOGD("Dropping event because the pointer is not down or we previously "
2105 "dropped the pointer down event in display %" PRId32,
2106 displayId);
2107 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002108 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 goto Failed;
2110 }
2111
arthurhung6d4bed92021-03-17 11:59:33 +08002112 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002113
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002115 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002116 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002117 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2118 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119
2120 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002121 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002122 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002123 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2124 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002125 if (DEBUG_FOCUS) {
2126 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2127 oldTouchedWindowHandle->getName().c_str(),
2128 newTouchedWindowHandle->getName().c_str(), displayId);
2129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002131 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2132 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2133 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134
2135 // Make a slippery entrance into the new window.
2136 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2137 isSplit = true;
2138 }
2139
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140 int32_t targetFlags =
2141 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 if (isSplit) {
2143 targetFlags |= InputTarget::FLAG_SPLIT;
2144 }
2145 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2146 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002147 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2148 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150
2151 BitSet32 pointerIds;
2152 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002153 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
2157 }
2158 }
2159
2160 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002161 // Let the previous window know that the hover sequence is over, unless we already did it
2162 // when dispatching it as is to newTouchedWindowHandle.
2163 if (mLastHoverWindowHandle != nullptr &&
2164 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2165 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166#if DEBUG_HOVER
2167 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002168 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002170 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2171 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 }
2173
Garfield Tandf26e862020-07-01 20:18:19 -07002174 // Let the new window know that the hover sequence is starting, unless we already did it
2175 // when dispatching it as is to newTouchedWindowHandle.
2176 if (newHoverWindowHandle != nullptr &&
2177 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2178 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179#if DEBUG_HOVER
2180 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002181 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002183 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2184 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2185 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187 }
2188
2189 // Check permission to inject into all touched foreground windows and ensure there
2190 // is at least one touched foreground window.
2191 {
2192 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002193 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2195 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002196 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002197 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 injectionPermission = INJECTION_PERMISSION_DENIED;
2199 goto Failed;
2200 }
2201 }
2202 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002203 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002204 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002205 ALOGI("Dropping event because there is no touched foreground window in display "
2206 "%" PRId32 " or gesture monitor to receive it.",
2207 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002208 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 goto Failed;
2210 }
2211
2212 // Permission granted to injection into all touched foreground windows.
2213 injectionPermission = INJECTION_PERMISSION_GRANTED;
2214 }
2215
2216 // Check whether windows listening for outside touches are owned by the same UID. If it is
2217 // set the policy flag that we will not reveal coordinate information to this window.
2218 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2219 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002220 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002221 if (foregroundWindowHandle) {
2222 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002223 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002224 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2225 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2226 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2228 InputTarget::FLAG_ZERO_COORDS,
2229 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 }
2232 }
2233 }
2234 }
2235
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 // If this is the first pointer going down and the touched window has a wallpaper
2237 // then also add the touched wallpaper windows so they are locked in for the duration
2238 // of the touch gesture.
2239 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2240 // engine only supports touch events. We would need to add a mechanism similar
2241 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2242 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2243 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002244 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002245 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002246 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002247 getWindowHandlesLocked(displayId);
2248 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002251 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002253 .addOrUpdateWindow(windowHandle,
2254 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2255 InputTarget::
2256 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2257 InputTarget::FLAG_DISPATCH_AS_IS,
2258 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 }
2260 }
2261 }
2262 }
2263
2264 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002265 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002273 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002275 }
2276
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 // Drop the outside or hover touch windows since we will not care about them
2278 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002279 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280
2281Failed:
2282 // Check injection permission once and for all.
2283 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002284 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 injectionPermission = INJECTION_PERMISSION_GRANTED;
2286 } else {
2287 injectionPermission = INJECTION_PERMISSION_DENIED;
2288 }
2289 }
2290
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002291 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2292 return injectionResult;
2293 }
2294
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002296 if (!wrongDevice) {
2297 if (switchedDevice) {
2298 if (DEBUG_FOCUS) {
2299 ALOGD("Conflicting pointer actions: Switched to a different device.");
2300 }
2301 *outConflictingPointerActions = true;
2302 }
2303
2304 if (isHoverAction) {
2305 // Started hovering, therefore no longer down.
2306 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002307 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002308 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2309 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 *outConflictingPointerActions = true;
2312 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002313 tempTouchState.reset();
2314 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2315 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2316 tempTouchState.deviceId = entry.deviceId;
2317 tempTouchState.source = entry.source;
2318 tempTouchState.displayId = displayId;
2319 }
2320 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2321 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2322 // All pointers up or canceled.
2323 tempTouchState.reset();
2324 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2325 // First pointer went down.
2326 if (oldState && oldState->down) {
2327 if (DEBUG_FOCUS) {
2328 ALOGD("Conflicting pointer actions: Down received while already down.");
2329 }
2330 *outConflictingPointerActions = true;
2331 }
2332 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2333 // One pointer went up.
2334 if (isSplit) {
2335 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2336 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002338 for (size_t i = 0; i < tempTouchState.windows.size();) {
2339 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2340 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2341 touchedWindow.pointerIds.clearBit(pointerId);
2342 if (touchedWindow.pointerIds.isEmpty()) {
2343 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2344 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002347 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002349 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002350 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002351
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002352 // Save changes unless the action was scroll in which case the temporary touch
2353 // state was only valid for this one action.
2354 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2355 if (tempTouchState.displayId >= 0) {
2356 mTouchStatesByDisplay[displayId] = tempTouchState;
2357 } else {
2358 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002362 // Update hover state.
2363 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 }
2365
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 return injectionResult;
2367}
2368
arthurhung6d4bed92021-03-17 11:59:33 +08002369void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2370 const sp<InputWindowHandle> dropWindow =
2371 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2372 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2373 true /*ignoreDragWindow*/);
2374 if (dropWindow) {
2375 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2376 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002377 } else {
2378 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002379 }
2380 mDragState.reset();
2381}
2382
2383void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2384 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002385 return;
2386 }
2387
arthurhung6d4bed92021-03-17 11:59:33 +08002388 if (!mDragState->isStartDrag) {
2389 mDragState->isStartDrag = true;
2390 mDragState->isStylusButtonDownAtStart =
2391 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2392 }
2393
arthurhungb89ccb02020-12-30 16:19:01 +08002394 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2395 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2396 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2397 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002398 // Handle the special case : stylus button no longer pressed.
2399 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2400 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2401 finishDragAndDrop(entry.displayId, x, y);
2402 return;
2403 }
2404
arthurhungb89ccb02020-12-30 16:19:01 +08002405 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002406 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002407 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2408 true /*ignoreDragWindow*/);
2409 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002410 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2411 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2412 if (mDragState->dragHoverWindowHandle != nullptr) {
2413 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2414 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002415 }
arthurhung6d4bed92021-03-17 11:59:33 +08002416 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002417 }
2418 // enqueue drag location if needed.
2419 if (hoverWindowHandle != nullptr) {
2420 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2421 }
arthurhung6d4bed92021-03-17 11:59:33 +08002422 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2423 finishDragAndDrop(entry.displayId, x, y);
2424 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002425 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002426 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002427 }
2428}
2429
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002431 int32_t targetFlags, BitSet32 pointerIds,
2432 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002433 std::vector<InputTarget>::iterator it =
2434 std::find_if(inputTargets.begin(), inputTargets.end(),
2435 [&windowHandle](const InputTarget& inputTarget) {
2436 return inputTarget.inputChannel->getConnectionToken() ==
2437 windowHandle->getToken();
2438 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002439
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002440 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002441
2442 if (it == inputTargets.end()) {
2443 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002444 std::shared_ptr<InputChannel> inputChannel =
2445 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002446 if (inputChannel == nullptr) {
2447 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2448 return;
2449 }
2450 inputTarget.inputChannel = inputChannel;
2451 inputTarget.flags = targetFlags;
2452 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002453 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002454 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002455 inputTargets.push_back(inputTarget);
2456 it = inputTargets.end() - 1;
2457 }
2458
2459 ALOG_ASSERT(it->flags == targetFlags);
2460 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2461
chaviw1ff3d1e2020-07-01 15:53:47 -07002462 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463}
2464
Michael Wright3dd60e22019-03-27 22:06:44 +00002465void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002466 int32_t displayId, float xOffset,
2467 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002468 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2469 mGlobalMonitorsByDisplay.find(displayId);
2470
2471 if (it != mGlobalMonitorsByDisplay.end()) {
2472 const std::vector<Monitor>& monitors = it->second;
2473 for (const Monitor& monitor : monitors) {
2474 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 }
2477}
2478
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002479void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2480 float yOffset,
2481 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002482 InputTarget target;
2483 target.inputChannel = monitor.inputChannel;
2484 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002485 ui::Transform t;
2486 t.set(xOffset, yOffset);
2487 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002488 inputTargets.push_back(target);
2489}
2490
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002492 const InjectionState* injectionState) {
2493 if (injectionState &&
2494 (windowHandle == nullptr ||
2495 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2496 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002497 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499 "owned by uid %d",
2500 injectionState->injectorPid, injectionState->injectorUid,
2501 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 } else {
2503 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506 return false;
2507 }
2508 return true;
2509}
2510
Robert Carrc9bf1d32020-04-13 17:21:08 -07002511/**
2512 * Indicate whether one window handle should be considered as obscuring
2513 * another window handle. We only check a few preconditions. Actually
2514 * checking the bounds is left to the caller.
2515 */
2516static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2517 const sp<InputWindowHandle>& otherHandle) {
2518 // Compare by token so cloned layers aren't counted
2519 if (haveSameToken(windowHandle, otherHandle)) {
2520 return false;
2521 }
2522 auto info = windowHandle->getInfo();
2523 auto otherInfo = otherHandle->getInfo();
2524 if (!otherInfo->visible) {
2525 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002526 } else if (otherInfo->alpha == 0 &&
2527 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2528 // Those act as if they were invisible, so we don't need to flag them.
2529 // We do want to potentially flag touchable windows even if they have 0
2530 // opacity, since they can consume touches and alter the effects of the
2531 // user interaction (eg. apps that rely on
2532 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2533 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2534 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002535 } else if (info->ownerUid == otherInfo->ownerUid) {
2536 // If ownerUid is the same we don't generate occlusion events as there
2537 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002538 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002539 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002540 return false;
2541 } else if (otherInfo->displayId != info->displayId) {
2542 return false;
2543 }
2544 return true;
2545}
2546
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002547/**
2548 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2549 * untrusted, one should check:
2550 *
2551 * 1. If result.hasBlockingOcclusion is true.
2552 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2553 * BLOCK_UNTRUSTED.
2554 *
2555 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2556 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2557 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2558 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2559 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2560 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2561 *
2562 * If neither of those is true, then it means the touch can be allowed.
2563 */
2564InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2565 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002566 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2567 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002568 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2569 TouchOcclusionInfo info;
2570 info.hasBlockingOcclusion = false;
2571 info.obscuringOpacity = 0;
2572 info.obscuringUid = -1;
2573 std::map<int32_t, float> opacityByUid;
2574 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2575 if (windowHandle == otherHandle) {
2576 break; // All future windows are below us. Exit early.
2577 }
2578 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002579 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2580 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002581 if (DEBUG_TOUCH_OCCLUSION) {
2582 info.debugInfo.push_back(
2583 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2584 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002585 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2586 // we perform the checks below to see if the touch can be propagated or not based on the
2587 // window's touch occlusion mode
2588 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2589 info.hasBlockingOcclusion = true;
2590 info.obscuringUid = otherInfo->ownerUid;
2591 info.obscuringPackage = otherInfo->packageName;
2592 break;
2593 }
2594 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2595 uint32_t uid = otherInfo->ownerUid;
2596 float opacity =
2597 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2598 // Given windows A and B:
2599 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2600 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2601 opacityByUid[uid] = opacity;
2602 if (opacity > info.obscuringOpacity) {
2603 info.obscuringOpacity = opacity;
2604 info.obscuringUid = uid;
2605 info.obscuringPackage = otherInfo->packageName;
2606 }
2607 }
2608 }
2609 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002610 if (DEBUG_TOUCH_OCCLUSION) {
2611 info.debugInfo.push_back(
2612 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2613 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002614 return info;
2615}
2616
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002617std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2618 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002619 return StringPrintf(INDENT2
2620 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2621 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2622 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2623 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002624 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002625 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002626 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002627 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2628 info->frameTop, info->frameRight, info->frameBottom,
2629 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002630 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2631 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2632 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002633}
2634
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002635bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2636 if (occlusionInfo.hasBlockingOcclusion) {
2637 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2638 occlusionInfo.obscuringUid);
2639 return false;
2640 }
2641 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2642 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2643 "%.2f, maximum allowed = %.2f)",
2644 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2645 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2646 return false;
2647 }
2648 return true;
2649}
2650
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002651bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2652 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002654 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002655 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002656 if (windowHandle == otherHandle) {
2657 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002660 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002661 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 return true;
2663 }
2664 }
2665 return false;
2666}
2667
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002668bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2669 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002670 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002671 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002672 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002673 if (windowHandle == otherHandle) {
2674 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002675 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002676 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002677 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002678 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002679 return true;
2680 }
2681 }
2682 return false;
2683}
2684
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002685std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002686 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002688 if (applicationHandle != nullptr) {
2689 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002690 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 } else {
2692 return applicationHandle->getName();
2693 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002694 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002695 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002697 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 }
2699}
2700
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002701void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002702 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002703 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2704 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002705 // Focus or pointer capture changed events are passed to apps, but do not represent user
2706 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002707 return;
2708 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002709 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002710 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002711 if (focusedWindowHandle != nullptr) {
2712 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002713 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002715 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716#endif
2717 return;
2718 }
2719 }
2720
2721 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002722 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002723 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002724 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2725 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 return;
2727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002729 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 eventType = USER_ACTIVITY_EVENT_TOUCH;
2731 }
2732 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002734 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002735 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2736 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 return;
2738 }
2739 eventType = USER_ACTIVITY_EVENT_BUTTON;
2740 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002742 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002743 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002744 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002745 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002746 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2747 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002748 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002749 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002750 break;
2751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
2753
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002754 std::unique_ptr<CommandEntry> commandEntry =
2755 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002756 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002758 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002759 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760}
2761
2762void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002764 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002765 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002766 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002767 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002768 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002769 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002770 ATRACE_NAME(message.c_str());
2771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772#if DEBUG_DISPATCH_CYCLE
2773 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002774 "globalScaleFactor=%f, pointerIds=0x%x %s",
2775 connection->getInputChannelName().c_str(), inputTarget.flags,
2776 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2777 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778#endif
2779
2780 // Skip this event if the connection status is not normal.
2781 // We don't want to enqueue additional outbound events if the connection is broken.
2782 if (connection->status != Connection::STATUS_NORMAL) {
2783#if DEBUG_DISPATCH_CYCLE
2784 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786#endif
2787 return;
2788 }
2789
2790 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002791 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2792 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2793 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002794 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002796 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002797 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002798 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002799 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 if (!splitMotionEntry) {
2801 return; // split event was dropped
2802 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002803 if (DEBUG_FOCUS) {
2804 ALOGD("channel '%s' ~ Split motion event.",
2805 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002806 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002807 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002808 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2809 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 return;
2811 }
2812 }
2813
2814 // Not splitting. Enqueue dispatch entries for the event as is.
2815 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2816}
2817
2818void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002819 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002820 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002821 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002822 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002824 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002825 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002826 ATRACE_NAME(message.c_str());
2827 }
2828
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002829 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830
2831 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002832 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002834 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002836 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002840 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844
2845 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002846 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 startDispatchCycleLocked(currentTime, connection);
2848 }
2849}
2850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002852 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002853 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002855 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002856 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2857 connection->getInputChannelName().c_str(),
2858 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002859 ATRACE_NAME(message.c_str());
2860 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002861 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 if (!(inputTargetFlags & dispatchMode)) {
2863 return;
2864 }
2865 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2866
2867 // This is a new event.
2868 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002869 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002872 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2873 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002874 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002876 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002877 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002878 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002879 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002880 dispatchEntry->resolvedAction = keyEntry.action;
2881 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002883 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2884 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2887 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 return; // skip the inconsistent event
2890 }
2891 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002894 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002895 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002896 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2897 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2898 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2899 static_cast<int32_t>(IdGenerator::Source::OTHER);
2900 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2902 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2903 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2904 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2905 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2906 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2907 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2908 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2909 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2910 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2911 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002913 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 }
2915 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002916 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2917 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2920 "event",
2921 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002923 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2924 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002928 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2930 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2931 }
2932 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2933 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2937 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2940 "event",
2941 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 return; // skip the inconsistent event
2944 }
2945
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002946 dispatchEntry->resolvedEventId =
2947 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2948 ? mIdGenerator.nextId()
2949 : motionEntry.id;
2950 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2951 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2952 ") to MotionEvent(id=0x%" PRIx32 ").",
2953 motionEntry.id, dispatchEntry->resolvedEventId);
2954 ATRACE_NAME(message.c_str());
2955 }
2956
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002957 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2958 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2959 // Skip reporting pointer down outside focus to the policy.
2960 break;
2961 }
2962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002963 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002964 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965
2966 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002968 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002969 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2970 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002971 break;
2972 }
Chris Yef59a2f42020-10-16 12:55:26 -07002973 case EventEntry::Type::SENSOR: {
2974 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2975 break;
2976 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002977 case EventEntry::Type::CONFIGURATION_CHANGED:
2978 case EventEntry::Type::DEVICE_RESET: {
2979 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002980 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002981 break;
2982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983 }
2984
2985 // Remember that we are waiting for this dispatch to complete.
2986 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002987 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
2989
2990 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002991 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002992 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002993}
2994
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002995/**
2996 * This function is purely for debugging. It helps us understand where the user interaction
2997 * was taking place. For example, if user is touching launcher, we will see a log that user
2998 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2999 * We will see both launcher and wallpaper in that list.
3000 * Once the interaction with a particular set of connections starts, no new logs will be printed
3001 * until the set of interacted connections changes.
3002 *
3003 * The following items are skipped, to reduce the logspam:
3004 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3005 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3006 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3007 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3008 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003009 */
3010void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3011 const std::vector<InputTarget>& targets) {
3012 // Skip ACTION_UP events, and all events other than keys and motions
3013 if (entry.type == EventEntry::Type::KEY) {
3014 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3015 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3016 return;
3017 }
3018 } else if (entry.type == EventEntry::Type::MOTION) {
3019 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3020 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3021 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3022 return;
3023 }
3024 } else {
3025 return; // Not a key or a motion
3026 }
3027
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003028 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003029 std::vector<sp<Connection>> newConnections;
3030 for (const InputTarget& target : targets) {
3031 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3032 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3033 continue; // Skip windows that receive ACTION_OUTSIDE
3034 }
3035
3036 sp<IBinder> token = target.inputChannel->getConnectionToken();
3037 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003038 if (connection == nullptr) {
3039 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003040 }
3041 newConnectionTokens.insert(std::move(token));
3042 newConnections.emplace_back(connection);
3043 }
3044 if (newConnectionTokens == mInteractionConnectionTokens) {
3045 return; // no change
3046 }
3047 mInteractionConnectionTokens = newConnectionTokens;
3048
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003049 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003050 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003051 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003052 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003053 std::string message = "Interaction with: " + targetList;
3054 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003055 message += "<none>";
3056 }
3057 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3058}
3059
chaviwfd6d3512019-03-25 13:23:49 -07003060void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003061 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003062 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003063 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3064 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003065 return;
3066 }
3067
Vishnu Nairc519ff72021-01-21 08:23:08 -08003068 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003069 if (focusedToken == token) {
3070 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003071 return;
3072 }
3073
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003074 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3075 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003076 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003077 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078}
3079
3080void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003082 if (ATRACE_ENABLED()) {
3083 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003085 ATRACE_NAME(message.c_str());
3086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#endif
3090
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003091 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3092 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003094 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003095 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003096 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
3098 // Publish the event.
3099 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003100 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3101 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003102 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003103 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3104 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003107 status = connection->inputPublisher
3108 .publishKeyEvent(dispatchEntry->seq,
3109 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3110 keyEntry.source, keyEntry.displayId,
3111 std::move(hmac), dispatchEntry->resolvedAction,
3112 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3113 keyEntry.scanCode, keyEntry.metaState,
3114 keyEntry.repeatCount, keyEntry.downTime,
3115 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003119 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003120 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003123 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124
chaviw82357092020-01-28 13:13:06 -08003125 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3128 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003129 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003130 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3131 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003132 // Don't apply window scale here since we don't want scale to affect raw
3133 // coordinates. The scale will be sent back to the client and applied
3134 // later when requesting relative coordinates.
3135 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3136 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 }
3138 usingCoords = scaledCoords;
3139 }
3140 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 // We don't want the dispatch target to know.
3142 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003143 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 scaledCoords[i].clear();
3145 }
3146 usingCoords = scaledCoords;
3147 }
3148 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003150 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003151
3152 // Publish the motion event.
3153 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003154 .publishMotionEvent(dispatchEntry->seq,
3155 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003156 motionEntry.deviceId, motionEntry.source,
3157 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003158 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003159 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 motionEntry.edgeFlags, motionEntry.metaState,
3162 motionEntry.buttonState,
3163 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003164 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 motionEntry.xPrecision, motionEntry.yPrecision,
3166 motionEntry.xCursorPosition,
3167 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003168 dispatchEntry->displaySize.x,
3169 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003170 motionEntry.downTime, motionEntry.eventTime,
3171 motionEntry.pointerCount,
3172 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003173 break;
3174 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003175
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003176 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003177 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003178 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003179 focusEntry.id,
3180 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003181 mInTouchMode);
3182 break;
3183 }
3184
Prabir Pradhan99987712020-11-10 18:43:05 -08003185 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3186 const auto& captureEntry =
3187 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3188 status = connection->inputPublisher
3189 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3190 captureEntry.pointerCaptureEnabled);
3191 break;
3192 }
3193
arthurhungb89ccb02020-12-30 16:19:01 +08003194 case EventEntry::Type::DRAG: {
3195 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3196 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3197 dragEntry.id, dragEntry.x,
3198 dragEntry.y,
3199 dragEntry.isExiting);
3200 break;
3201 }
3202
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003203 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003204 case EventEntry::Type::DEVICE_RESET:
3205 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003206 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003207 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
3211
3212 // Check the result.
3213 if (status) {
3214 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003215 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 "This is unexpected because the wait queue is empty, so the pipe "
3218 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003219 "event to it, status=%s(%d)",
3220 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3221 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3223 } else {
3224 // Pipe is full and we are waiting for the app to finish process some events
3225 // before sending more events to it.
3226#if DEBUG_DISPATCH_CYCLE
3227 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 "waiting for the application to catch up",
3229 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232 } else {
3233 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003234 "status=%s(%d)",
3235 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3236 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3238 }
3239 return;
3240 }
3241
3242 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003243 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3244 connection->outboundQueue.end(),
3245 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003246 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003247 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003248 if (connection->responsive) {
3249 mAnrTracker.insert(dispatchEntry->timeoutTime,
3250 connection->inputChannel->getConnectionToken());
3251 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003252 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 }
3254}
3255
chaviw09c8d2d2020-08-24 15:48:26 -07003256std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3257 size_t size;
3258 switch (event.type) {
3259 case VerifiedInputEvent::Type::KEY: {
3260 size = sizeof(VerifiedKeyEvent);
3261 break;
3262 }
3263 case VerifiedInputEvent::Type::MOTION: {
3264 size = sizeof(VerifiedMotionEvent);
3265 break;
3266 }
3267 }
3268 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3269 return mHmacKeyManager.sign(start, size);
3270}
3271
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003272const std::array<uint8_t, 32> InputDispatcher::getSignature(
3273 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3274 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3275 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3276 // Only sign events up and down events as the purely move events
3277 // are tied to their up/down counterparts so signing would be redundant.
3278 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3279 verifiedEvent.actionMasked = actionMasked;
3280 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003281 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003282 }
3283 return INVALID_HMAC;
3284}
3285
3286const std::array<uint8_t, 32> InputDispatcher::getSignature(
3287 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3288 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3289 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3290 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003291 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003292}
3293
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003296 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297#if DEBUG_DISPATCH_CYCLE
3298 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300#endif
3301
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 if (connection->status == Connection::STATUS_BROKEN ||
3303 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 return;
3305 }
3306
3307 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003308 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309}
3310
3311void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 const sp<Connection>& connection,
3313 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314#if DEBUG_DISPATCH_CYCLE
3315 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317#endif
3318
3319 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003320 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003321 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003322 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003323 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
3325 // The connection appears to be unrecoverably broken.
3326 // Ignore already broken or zombie connections.
3327 if (connection->status == Connection::STATUS_NORMAL) {
3328 connection->status = Connection::STATUS_BROKEN;
3329
3330 if (notify) {
3331 // Notify other system components.
3332 onDispatchCycleBrokenLocked(currentTime, connection);
3333 }
3334 }
3335}
3336
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003337void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3338 while (!queue.empty()) {
3339 DispatchEntry* dispatchEntry = queue.front();
3340 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003341 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
3343}
3344
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003345void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003347 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 }
3349 delete dispatchEntry;
3350}
3351
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003352int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3353 std::scoped_lock _l(mLock);
3354 sp<Connection> connection = getConnectionLocked(connectionToken);
3355 if (connection == nullptr) {
3356 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3357 connectionToken.get(), events);
3358 return 0; // remove the callback
3359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003361 bool notify;
3362 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3363 if (!(events & ALOOPER_EVENT_INPUT)) {
3364 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3365 "events=0x%x",
3366 connection->getInputChannelName().c_str(), events);
3367 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 }
3369
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003370 nsecs_t currentTime = now();
3371 bool gotOne = false;
3372 status_t status = OK;
3373 for (;;) {
3374 Result<InputPublisher::ConsumerResponse> result =
3375 connection->inputPublisher.receiveConsumerResponse();
3376 if (!result.ok()) {
3377 status = result.error().code();
3378 break;
3379 }
3380
3381 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3382 const InputPublisher::Finished& finish =
3383 std::get<InputPublisher::Finished>(*result);
3384 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3385 finish.consumeTime);
3386 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003387 if (shouldReportMetricsForConnection(*connection)) {
3388 const InputPublisher::Timeline& timeline =
3389 std::get<InputPublisher::Timeline>(*result);
3390 mLatencyTracker
3391 .trackGraphicsLatency(timeline.inputEventId,
3392 connection->inputChannel->getConnectionToken(),
3393 std::move(timeline.graphicsTimeline));
3394 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003395 }
3396 gotOne = true;
3397 }
3398 if (gotOne) {
3399 runCommandsLockedInterruptible();
3400 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 return 1;
3402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 }
3404
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003405 notify = status != DEAD_OBJECT || !connection->monitor;
3406 if (notify) {
3407 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3408 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3409 status);
3410 }
3411 } else {
3412 // Monitor channels are never explicitly unregistered.
3413 // We do it automatically when the remote endpoint is closed so don't warn about them.
3414 const bool stillHaveWindowHandle =
3415 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3416 notify = !connection->monitor && stillHaveWindowHandle;
3417 if (notify) {
3418 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3419 connection->getInputChannelName().c_str(), events);
3420 }
3421 }
3422
3423 // Remove the channel.
3424 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3425 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426}
3427
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003430 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003431 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433}
3434
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003436 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003437 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3438 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3439}
3440
3441void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3442 const CancelationOptions& options,
3443 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3444 for (const auto& it : monitorsByDisplay) {
3445 const std::vector<Monitor>& monitors = it.second;
3446 for (const Monitor& monitor : monitors) {
3447 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003448 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003449 }
3450}
3451
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003453 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003454 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003455 if (connection == nullptr) {
3456 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003458
3459 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460}
3461
3462void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3463 const sp<Connection>& connection, const CancelationOptions& options) {
3464 if (connection->status == Connection::STATUS_BROKEN) {
3465 return;
3466 }
3467
3468 nsecs_t currentTime = now();
3469
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003470 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003471 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003473 if (cancelationEvents.empty()) {
3474 return;
3475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003477 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3478 "with reality: %s, mode=%d.",
3479 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3480 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003482
3483 InputTarget target;
3484 sp<InputWindowHandle> windowHandle =
3485 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3486 if (windowHandle != nullptr) {
3487 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003488 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003489 target.globalScaleFactor = windowInfo->globalScaleFactor;
3490 }
3491 target.inputChannel = connection->inputChannel;
3492 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3493
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003494 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003495 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003496 switch (cancelationEventEntry->type) {
3497 case EventEntry::Type::KEY: {
3498 logOutboundKeyDetails("cancel - ",
3499 static_cast<const KeyEntry&>(*cancelationEventEntry));
3500 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003502 case EventEntry::Type::MOTION: {
3503 logOutboundMotionDetails("cancel - ",
3504 static_cast<const MotionEntry&>(*cancelationEventEntry));
3505 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003507 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003508 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3509 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003510 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003511 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003512 break;
3513 }
3514 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003515 case EventEntry::Type::DEVICE_RESET:
3516 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003517 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003518 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003519 break;
3520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 }
3522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003523 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3524 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003526
3527 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528}
3529
Svet Ganov5d3bc372020-01-26 23:11:07 -08003530void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3531 const sp<Connection>& connection) {
3532 if (connection->status == Connection::STATUS_BROKEN) {
3533 return;
3534 }
3535
3536 nsecs_t currentTime = now();
3537
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003538 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003539 connection->inputState.synthesizePointerDownEvents(currentTime);
3540
3541 if (downEvents.empty()) {
3542 return;
3543 }
3544
3545#if DEBUG_OUTBOUND_EVENT_DETAILS
3546 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3547 connection->getInputChannelName().c_str(), downEvents.size());
3548#endif
3549
3550 InputTarget target;
3551 sp<InputWindowHandle> windowHandle =
3552 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3553 if (windowHandle != nullptr) {
3554 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003555 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003556 target.globalScaleFactor = windowInfo->globalScaleFactor;
3557 }
3558 target.inputChannel = connection->inputChannel;
3559 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3560
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003561 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003562 switch (downEventEntry->type) {
3563 case EventEntry::Type::MOTION: {
3564 logOutboundMotionDetails("down - ",
3565 static_cast<const MotionEntry&>(*downEventEntry));
3566 break;
3567 }
3568
3569 case EventEntry::Type::KEY:
3570 case EventEntry::Type::FOCUS:
3571 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003572 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003573 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003574 case EventEntry::Type::SENSOR:
3575 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003576 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003577 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003578 break;
3579 }
3580 }
3581
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003582 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3583 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003584 }
3585
3586 startDispatchCycleLocked(currentTime, connection);
3587}
3588
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003589std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3590 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 ALOG_ASSERT(pointerIds.value != 0);
3592
3593 uint32_t splitPointerIndexMap[MAX_POINTERS];
3594 PointerProperties splitPointerProperties[MAX_POINTERS];
3595 PointerCoords splitPointerCoords[MAX_POINTERS];
3596
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003597 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 uint32_t splitPointerCount = 0;
3599
3600 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003601 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003603 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 uint32_t pointerId = uint32_t(pointerProperties.id);
3605 if (pointerIds.hasBit(pointerId)) {
3606 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3607 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3608 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003609 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 splitPointerCount += 1;
3611 }
3612 }
3613
3614 if (splitPointerCount != pointerIds.count()) {
3615 // This is bad. We are missing some of the pointers that we expected to deliver.
3616 // Most likely this indicates that we received an ACTION_MOVE events that has
3617 // different pointer ids than we expected based on the previous ACTION_DOWN
3618 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3619 // in this way.
3620 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003621 "we expected there to be %d pointers. This probably means we received "
3622 "a broken sequence of pointer ids from the input device.",
3623 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003624 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003627 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003629 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3630 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3632 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003633 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 uint32_t pointerId = uint32_t(pointerProperties.id);
3635 if (pointerIds.hasBit(pointerId)) {
3636 if (pointerIds.count() == 1) {
3637 // The first/last pointer went down/up.
3638 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003639 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003640 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3641 ? AMOTION_EVENT_ACTION_CANCEL
3642 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 } else {
3644 // A secondary pointer went down/up.
3645 uint32_t splitPointerIndex = 0;
3646 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3647 splitPointerIndex += 1;
3648 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003649 action = maskedAction |
3650 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 }
3652 } else {
3653 // An unrelated pointer changed.
3654 action = AMOTION_EVENT_ACTION_MOVE;
3655 }
3656 }
3657
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003658 int32_t newId = mIdGenerator.nextId();
3659 if (ATRACE_ENABLED()) {
3660 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3661 ") to MotionEvent(id=0x%" PRIx32 ").",
3662 originalMotionEntry.id, newId);
3663 ATRACE_NAME(message.c_str());
3664 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003665 std::unique_ptr<MotionEntry> splitMotionEntry =
3666 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3667 originalMotionEntry.deviceId, originalMotionEntry.source,
3668 originalMotionEntry.displayId,
3669 originalMotionEntry.policyFlags, action,
3670 originalMotionEntry.actionButton,
3671 originalMotionEntry.flags, originalMotionEntry.metaState,
3672 originalMotionEntry.buttonState,
3673 originalMotionEntry.classification,
3674 originalMotionEntry.edgeFlags,
3675 originalMotionEntry.xPrecision,
3676 originalMotionEntry.yPrecision,
3677 originalMotionEntry.xCursorPosition,
3678 originalMotionEntry.yCursorPosition,
3679 originalMotionEntry.downTime, splitPointerCount,
3680 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003682 if (originalMotionEntry.injectionState) {
3683 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 splitMotionEntry->injectionState->refCount += 1;
3685 }
3686
3687 return splitMotionEntry;
3688}
3689
3690void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3691#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003692 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693#endif
3694
3695 bool needWake;
3696 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003697 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003699 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3700 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3701 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 } // release lock
3703
3704 if (needWake) {
3705 mLooper->wake();
3706 }
3707}
3708
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003709/**
3710 * If one of the meta shortcuts is detected, process them here:
3711 * Meta + Backspace -> generate BACK
3712 * Meta + Enter -> generate HOME
3713 * This will potentially overwrite keyCode and metaState.
3714 */
3715void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003716 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003717 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3718 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3719 if (keyCode == AKEYCODE_DEL) {
3720 newKeyCode = AKEYCODE_BACK;
3721 } else if (keyCode == AKEYCODE_ENTER) {
3722 newKeyCode = AKEYCODE_HOME;
3723 }
3724 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003725 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003726 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003727 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003728 keyCode = newKeyCode;
3729 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3730 }
3731 } else if (action == AKEY_EVENT_ACTION_UP) {
3732 // In order to maintain a consistent stream of up and down events, check to see if the key
3733 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3734 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003735 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003736 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003737 auto replacementIt = mReplacedKeys.find(replacement);
3738 if (replacementIt != mReplacedKeys.end()) {
3739 keyCode = replacementIt->second;
3740 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003741 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3742 }
3743 }
3744}
3745
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3747#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003748 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3749 "policyFlags=0x%x, action=0x%x, "
3750 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3751 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3752 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3753 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754#endif
3755 if (!validateKeyEvent(args->action)) {
3756 return;
3757 }
3758
3759 uint32_t policyFlags = args->policyFlags;
3760 int32_t flags = args->flags;
3761 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003762 // InputDispatcher tracks and generates key repeats on behalf of
3763 // whatever notifies it, so repeatCount should always be set to 0
3764 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3766 policyFlags |= POLICY_FLAG_VIRTUAL;
3767 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 if (policyFlags & POLICY_FLAG_FUNCTION) {
3770 metaState |= AMETA_FUNCTION_ON;
3771 }
3772
3773 policyFlags |= POLICY_FLAG_TRUSTED;
3774
Michael Wright78f24442014-08-06 15:55:28 -07003775 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003776 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003777
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003779 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003780 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3781 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782
Michael Wright2b3c3302018-03-02 17:19:13 +00003783 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003785 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3786 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 bool needWake;
3791 { // acquire lock
3792 mLock.lock();
3793
3794 if (shouldSendKeyToInputFilterLocked(args)) {
3795 mLock.unlock();
3796
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003797 policyFlags |= POLICY_FLAG_FILTERED | POLICY_FLAG_INPUTFILTER_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3799 return; // event was consumed by the filter
3800 }
3801
3802 mLock.lock();
3803 }
3804
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003805 std::unique_ptr<KeyEntry> newEntry =
3806 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3807 args->displayId, policyFlags, args->action, flags,
3808 keyCode, args->scanCode, metaState, repeatCount,
3809 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003811 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 mLock.unlock();
3813 } // release lock
3814
3815 if (needWake) {
3816 mLooper->wake();
3817 }
3818}
3819
3820bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3821 return mInputFilterEnabled;
3822}
3823
3824void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3825#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003826 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3827 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003828 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3829 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003830 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003831 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3832 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3833 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3834 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 for (uint32_t i = 0; i < args->pointerCount; i++) {
3836 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003837 "x=%f, y=%f, pressure=%f, size=%f, "
3838 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3839 "orientation=%f",
3840 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3841 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3842 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3843 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3844 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3845 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3846 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3847 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3848 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3849 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003852 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3853 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 return;
3855 }
3856
3857 uint32_t policyFlags = args->policyFlags;
3858 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003859
3860 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003861 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003862 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3863 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003864 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866
3867 bool needWake;
3868 { // acquire lock
3869 mLock.lock();
3870
3871 if (shouldSendMotionToInputFilterLocked(args)) {
3872 mLock.unlock();
3873
3874 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003875 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003876 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3877 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003878 args->metaState, args->buttonState, args->classification, transform,
3879 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003880 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3881 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003882 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883
3884 policyFlags |= POLICY_FLAG_FILTERED;
3885 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3886 return; // event was consumed by the filter
3887 }
3888
3889 mLock.lock();
3890 }
3891
3892 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003893 std::unique_ptr<MotionEntry> newEntry =
3894 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3895 args->source, args->displayId, policyFlags,
3896 args->action, args->actionButton, args->flags,
3897 args->metaState, args->buttonState,
3898 args->classification, args->edgeFlags,
3899 args->xPrecision, args->yPrecision,
3900 args->xCursorPosition, args->yCursorPosition,
3901 args->downTime, args->pointerCount,
3902 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003904 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 mLock.unlock();
3906 } // release lock
3907
3908 if (needWake) {
3909 mLooper->wake();
3910 }
3911}
3912
Chris Yef59a2f42020-10-16 12:55:26 -07003913void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3914#if DEBUG_INBOUND_EVENT_DETAILS
3915 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3916 " sensorType=%s",
3917 args->id, args->eventTime, args->deviceId, args->source,
3918 NamedEnum::string(args->sensorType).c_str());
3919#endif
3920
3921 bool needWake;
3922 { // acquire lock
3923 mLock.lock();
3924
3925 // Just enqueue a new sensor event.
3926 std::unique_ptr<SensorEntry> newEntry =
3927 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3928 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3929 args->sensorType, args->accuracy,
3930 args->accuracyChanged, args->values);
3931
3932 needWake = enqueueInboundEventLocked(std::move(newEntry));
3933 mLock.unlock();
3934 } // release lock
3935
3936 if (needWake) {
3937 mLooper->wake();
3938 }
3939}
3940
Chris Yefb552902021-02-03 17:18:37 -08003941void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3942#if DEBUG_INBOUND_EVENT_DETAILS
3943 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3944 args->deviceId, args->isOn);
3945#endif
3946 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3947}
3948
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003950 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951}
3952
3953void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3954#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003955 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003956 "switchMask=0x%08x",
3957 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958#endif
3959
3960 uint32_t policyFlags = args->policyFlags;
3961 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963}
3964
3965void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3966#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3968 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969#endif
3970
3971 bool needWake;
3972 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003973 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003975 std::unique_ptr<DeviceResetEntry> newEntry =
3976 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3977 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 } // release lock
3979
3980 if (needWake) {
3981 mLooper->wake();
3982 }
3983}
3984
Prabir Pradhan7e186182020-11-10 13:56:45 -08003985void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3986#if DEBUG_INBOUND_EVENT_DETAILS
3987 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3988 args->enabled ? "true" : "false");
3989#endif
3990
Prabir Pradhan99987712020-11-10 18:43:05 -08003991 bool needWake;
3992 { // acquire lock
3993 std::scoped_lock _l(mLock);
3994 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3995 args->enabled);
3996 needWake = enqueueInboundEventLocked(std::move(entry));
3997 } // release lock
3998
3999 if (needWake) {
4000 mLooper->wake();
4001 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004002}
4003
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004004InputEventInjectionResult InputDispatcher::injectInputEvent(
4005 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4006 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007#if DEBUG_INBOUND_EVENT_DETAILS
4008 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004009 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4010 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004012 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
4014 policyFlags |= POLICY_FLAG_INJECTED;
4015 if (hasInjectionPermission(injectorPid, injectorUid)) {
4016 policyFlags |= POLICY_FLAG_TRUSTED;
4017 }
4018
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004019 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
4020 // that have gone through the InputFilter. If the event passed through the InputFilter,
4021 // but did not get modified, assign the provided device id. If the InputFilter modifies the
4022 // events in any way, it is responsible for removing this flag.
4023 // If the injected event originated from accessibility, assign the accessibility device id,
4024 // so that it can be distinguished from regular injected events.
4025 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
4026 if (policyFlags & POLICY_FLAG_INPUTFILTER_TRUSTED) {
4027 resolvedDeviceId = event->getDeviceId();
4028 } else if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4029 resolvedDeviceId = ACCESSIBILITY_DEVICE_ID;
4030 }
4031
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004032 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004034 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004035 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4036 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004037 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004038 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004041 int32_t flags = incomingKey.getFlags();
4042 int32_t keyCode = incomingKey.getKeyCode();
4043 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004044 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004045 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004046 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004047 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004048 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4049 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4050 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4053 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004054 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055
4056 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4057 android::base::Timer t;
4058 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4059 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4060 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4061 std::to_string(t.duration().count()).c_str());
4062 }
4063 }
4064
4065 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004066 std::unique_ptr<KeyEntry> injectedEntry =
4067 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004068 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069 incomingKey.getDisplayId(), policyFlags, action,
4070 flags, keyCode, incomingKey.getScanCode(), metaState,
4071 incomingKey.getRepeatCount(),
4072 incomingKey.getDownTime());
4073 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
4076
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004078 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4079 int32_t action = motionEvent.getAction();
4080 size_t pointerCount = motionEvent.getPointerCount();
4081 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4082 int32_t actionButton = motionEvent.getActionButton();
4083 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004084 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004085 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 }
4087
4088 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004089 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004090 android::base::Timer t;
4091 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4092 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4093 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4094 std::to_string(t.duration().count()).c_str());
4095 }
4096 }
4097
4098 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004099 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4100 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004101 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004102 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4103 resolvedDeviceId, motionEvent.getSource(),
4104 motionEvent.getDisplayId(), policyFlags, action,
4105 actionButton, motionEvent.getFlags(),
4106 motionEvent.getMetaState(),
4107 motionEvent.getButtonState(),
4108 motionEvent.getClassification(),
4109 motionEvent.getEdgeFlags(),
4110 motionEvent.getXPrecision(),
4111 motionEvent.getYPrecision(),
4112 motionEvent.getRawXCursorPosition(),
4113 motionEvent.getRawYCursorPosition(),
4114 motionEvent.getDownTime(), uint32_t(pointerCount),
4115 pointerProperties, samplePointerCoords,
4116 motionEvent.getXOffset(),
4117 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004119 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 sampleEventTimes += 1;
4121 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004122 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004123 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4124 resolvedDeviceId, motionEvent.getSource(),
4125 motionEvent.getDisplayId(), policyFlags,
4126 action, actionButton, motionEvent.getFlags(),
4127 motionEvent.getMetaState(),
4128 motionEvent.getButtonState(),
4129 motionEvent.getClassification(),
4130 motionEvent.getEdgeFlags(),
4131 motionEvent.getXPrecision(),
4132 motionEvent.getYPrecision(),
4133 motionEvent.getRawXCursorPosition(),
4134 motionEvent.getRawYCursorPosition(),
4135 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004136 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 samplePointerCoords, motionEvent.getXOffset(),
4138 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004139 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 }
4141 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004145 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004146 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 }
4148
4149 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004150 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 injectionState->injectionIsAsync = true;
4152 }
4153
4154 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004155 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156
4157 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004158 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004159 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004160 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 }
4162
4163 mLock.unlock();
4164
4165 if (needWake) {
4166 mLooper->wake();
4167 }
4168
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004169 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004171 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 if (syncMode == InputEventInjectionSync::NONE) {
4174 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 } else {
4176 for (;;) {
4177 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004178 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 break;
4180 }
4181
4182 nsecs_t remainingTimeout = endTime - now();
4183 if (remainingTimeout <= 0) {
4184#if DEBUG_INJECTION
4185 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004188 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 break;
4190 }
4191
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004192 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
4194
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004195 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4196 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 while (injectionState->pendingForegroundDispatches != 0) {
4198#if DEBUG_INJECTION
4199 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201#endif
4202 nsecs_t remainingTimeout = endTime - now();
4203 if (remainingTimeout <= 0) {
4204#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4206 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004208 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 break;
4210 }
4211
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004212 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 }
4214 }
4215 }
4216
4217 injectionState->release();
4218 } // release lock
4219
4220#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004221 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223#endif
4224
4225 return injectionResult;
4226}
4227
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004228std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004229 std::array<uint8_t, 32> calculatedHmac;
4230 std::unique_ptr<VerifiedInputEvent> result;
4231 switch (event.getType()) {
4232 case AINPUT_EVENT_TYPE_KEY: {
4233 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4234 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4235 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004236 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004237 break;
4238 }
4239 case AINPUT_EVENT_TYPE_MOTION: {
4240 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4241 VerifiedMotionEvent verifiedMotionEvent =
4242 verifiedMotionEventFromMotionEvent(motionEvent);
4243 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004244 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004245 break;
4246 }
4247 default: {
4248 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4249 return nullptr;
4250 }
4251 }
4252 if (calculatedHmac == INVALID_HMAC) {
4253 return nullptr;
4254 }
4255 if (calculatedHmac != event.getHmac()) {
4256 return nullptr;
4257 }
4258 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004259}
4260
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 return injectorUid == 0 ||
4263 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264}
4265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004266void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004267 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004268 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 if (injectionState) {
4270#if DEBUG_INJECTION
4271 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 "injectorPid=%d, injectorUid=%d",
4273 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274#endif
4275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 // Log the outcome since the injector did not wait for the injection result.
4278 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004279 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 ALOGV("Asynchronous input event injection succeeded.");
4281 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004282 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 ALOGW("Asynchronous input event injection failed.");
4284 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004285 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 ALOGW("Asynchronous input event injection permission denied.");
4287 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004288 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 ALOGW("Asynchronous input event injection timed out.");
4290 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004291 case InputEventInjectionResult::PENDING:
4292 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4293 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295 }
4296
4297 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004298 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 }
4300}
4301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004302void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4303 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 if (injectionState) {
4305 injectionState->pendingForegroundDispatches += 1;
4306 }
4307}
4308
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004309void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4310 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 if (injectionState) {
4312 injectionState->pendingForegroundDispatches -= 1;
4313
4314 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004315 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 }
4317 }
4318}
4319
Vishnu Nairad321cd2020-08-20 16:40:21 -07004320const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004321 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004322 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4323 auto it = mWindowHandlesByDisplay.find(displayId);
4324 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004325}
4326
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004328 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004329 if (windowHandleToken == nullptr) {
4330 return nullptr;
4331 }
4332
Arthur Hungb92218b2018-08-14 12:00:21 +08004333 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004334 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004335 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004336 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004337 return windowHandle;
4338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 }
4340 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004341 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342}
4343
Vishnu Nairad321cd2020-08-20 16:40:21 -07004344sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4345 int displayId) const {
4346 if (windowHandleToken == nullptr) {
4347 return nullptr;
4348 }
4349
4350 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4351 if (windowHandle->getToken() == windowHandleToken) {
4352 return windowHandle;
4353 }
4354 }
4355 return nullptr;
4356}
4357
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004358sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4359 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004360 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004361 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004362 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004363 if (handle->getId() == windowHandle->getId() &&
4364 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004365 if (windowHandle->getInfo()->displayId != it.first) {
4366 ALOGE("Found window %s in display %" PRId32
4367 ", but it should belong to display %" PRId32,
4368 windowHandle->getName().c_str(), it.first,
4369 windowHandle->getInfo()->displayId);
4370 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004371 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004375 return nullptr;
4376}
4377
4378sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4379 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4380 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381}
4382
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004383bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4384 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4385 const bool noInputChannel =
4386 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4387 if (connection != nullptr && noInputChannel) {
4388 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4389 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4390 return false;
4391 }
4392
4393 if (connection == nullptr) {
4394 if (!noInputChannel) {
4395 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4396 }
4397 return false;
4398 }
4399 if (!connection->responsive) {
4400 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4401 return false;
4402 }
4403 return true;
4404}
4405
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004406std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4407 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004408 auto connectionIt = mConnectionsByToken.find(token);
4409 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004410 return nullptr;
4411 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004412 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004413}
4414
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004415void InputDispatcher::updateWindowHandlesForDisplayLocked(
4416 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4417 if (inputWindowHandles.empty()) {
4418 // Remove all handles on a display if there are no windows left.
4419 mWindowHandlesByDisplay.erase(displayId);
4420 return;
4421 }
4422
4423 // Since we compare the pointer of input window handles across window updates, we need
4424 // to make sure the handle object for the same window stays unchanged across updates.
4425 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004426 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004427 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004428 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004429 }
4430
4431 std::vector<sp<InputWindowHandle>> newHandles;
4432 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4433 if (!handle->updateInfo()) {
4434 // handle no longer valid
4435 continue;
4436 }
4437
4438 const InputWindowInfo* info = handle->getInfo();
4439 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4440 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4441 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004442 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4443 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4444 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004445 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004446 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004447 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004448 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004449 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004450 }
4451
4452 if (info->displayId != displayId) {
4453 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4454 handle->getName().c_str(), displayId, info->displayId);
4455 continue;
4456 }
4457
Robert Carredd13602020-04-13 17:24:34 -07004458 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4459 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004460 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004461 oldHandle->updateFrom(handle);
4462 newHandles.push_back(oldHandle);
4463 } else {
4464 newHandles.push_back(handle);
4465 }
4466 }
4467
4468 // Insert or replace
4469 mWindowHandlesByDisplay[displayId] = newHandles;
4470}
4471
Arthur Hung72d8dc32020-03-28 00:48:39 +00004472void InputDispatcher::setInputWindows(
4473 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4474 { // acquire lock
4475 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004476 for (const auto& [displayId, handles] : handlesPerDisplay) {
4477 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004478 }
4479 }
4480 // Wake up poll loop since it may need to make new input dispatching choices.
4481 mLooper->wake();
4482}
4483
Arthur Hungb92218b2018-08-14 12:00:21 +08004484/**
4485 * Called from InputManagerService, update window handle list by displayId that can receive input.
4486 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4487 * If set an empty list, remove all handles from the specific display.
4488 * For focused handle, check if need to change and send a cancel event to previous one.
4489 * For removed handle, check if need to send a cancel event if already in touch.
4490 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004491void InputDispatcher::setInputWindowsLocked(
4492 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004493 if (DEBUG_FOCUS) {
4494 std::string windowList;
4495 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4496 windowList += iwh->getName() + " ";
4497 }
4498 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004501 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4502 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4503 const bool noInputWindow =
4504 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4505 if (noInputWindow && window->getToken() != nullptr) {
4506 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4507 window->getName().c_str());
4508 window->releaseChannel();
4509 }
4510 }
4511
Arthur Hung72d8dc32020-03-28 00:48:39 +00004512 // Copy old handles for release if they are no longer present.
4513 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004515 // Save the old windows' orientation by ID before it gets updated.
4516 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4517 for (const sp<InputWindowHandle>& handle : oldWindowHandles) {
4518 oldWindowOrientations.emplace(handle->getId(),
4519 handle->getInfo()->transform.getOrientation());
4520 }
4521
Arthur Hung72d8dc32020-03-28 00:48:39 +00004522 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004523
Vishnu Nair958da932020-08-21 17:12:37 -07004524 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4525 if (mLastHoverWindowHandle &&
4526 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4527 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004528 mLastHoverWindowHandle = nullptr;
4529 }
4530
Vishnu Nairc519ff72021-01-21 08:23:08 -08004531 std::optional<FocusResolver::FocusChanges> changes =
4532 mFocusResolver.setInputWindows(displayId, windowHandles);
4533 if (changes) {
4534 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004537 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4538 mTouchStatesByDisplay.find(displayId);
4539 if (stateIt != mTouchStatesByDisplay.end()) {
4540 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004541 for (size_t i = 0; i < state.windows.size();) {
4542 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004543 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004544 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004545 ALOGD("Touched window was removed: %s in display %" PRId32,
4546 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004547 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004548 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004549 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4550 if (touchedInputChannel != nullptr) {
4551 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4552 "touched window was removed");
4553 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004555 state.windows.erase(state.windows.begin() + i);
4556 } else {
4557 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559 }
arthurhungb89ccb02020-12-30 16:19:01 +08004560
arthurhung6d4bed92021-03-17 11:59:33 +08004561 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004562 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004563 if (mDragState &&
4564 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004565 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004566 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004567 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004568 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004569
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004570 if (isPerWindowInputRotationEnabled()) {
4571 // Determine if the orientation of any of the input windows have changed, and cancel all
4572 // pointer events if necessary.
4573 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
4574 const sp<InputWindowHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4575 if (newWindowHandle != nullptr &&
4576 newWindowHandle->getInfo()->transform.getOrientation() !=
4577 oldWindowOrientations[oldWindowHandle->getId()]) {
4578 std::shared_ptr<InputChannel> inputChannel =
4579 getInputChannelLocked(newWindowHandle->getToken());
4580 if (inputChannel != nullptr) {
4581 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4582 "touched window's orientation changed");
4583 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4584 }
4585 }
4586 }
4587 }
4588
Arthur Hung72d8dc32020-03-28 00:48:39 +00004589 // Release information for windows that are no longer present.
4590 // This ensures that unused input channels are released promptly.
4591 // Otherwise, they might stick around until the window handle is destroyed
4592 // which might not happen until the next GC.
4593 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004594 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004595 if (DEBUG_FOCUS) {
4596 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004597 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004598 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004599 // To avoid making too many calls into the compat framework, only
4600 // check for window flags when windows are going away.
4601 // TODO(b/157929241) : delete this. This is only needed temporarily
4602 // in order to gather some data about the flag usage
4603 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4604 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4605 oldWindowHandle->getName().c_str());
4606 if (mCompatService != nullptr) {
4607 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4608 oldWindowHandle->getInfo()->ownerUid);
4609 }
4610 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004611 }
chaviw291d88a2019-02-14 10:33:58 -08004612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613}
4614
4615void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004616 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004617 if (DEBUG_FOCUS) {
4618 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4619 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4620 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004621 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004622 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004623 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 } // release lock
4625
4626 // Wake up poll loop since it may need to make new input dispatching choices.
4627 mLooper->wake();
4628}
4629
Vishnu Nair599f1412021-06-21 10:39:58 -07004630void InputDispatcher::setFocusedApplicationLocked(
4631 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4632 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4633 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4634
4635 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4636 return; // This application is already focused. No need to wake up or change anything.
4637 }
4638
4639 // Set the new application handle.
4640 if (inputApplicationHandle != nullptr) {
4641 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4642 } else {
4643 mFocusedApplicationHandlesByDisplay.erase(displayId);
4644 }
4645
4646 // No matter what the old focused application was, stop waiting on it because it is
4647 // no longer focused.
4648 resetNoFocusedWindowTimeoutLocked();
4649}
4650
Tiger Huang721e26f2018-07-24 22:26:19 +08004651/**
4652 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4653 * the display not specified.
4654 *
4655 * We track any unreleased events for each window. If a window loses the ability to receive the
4656 * released event, we will send a cancel event to it. So when the focused display is changed, we
4657 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4658 * display. The display-specified events won't be affected.
4659 */
4660void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004661 if (DEBUG_FOCUS) {
4662 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4663 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004664 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004665 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004666
4667 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004668 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004669 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004670 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004671 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004672 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004673 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004674 CancelationOptions
4675 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4676 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004677 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004678 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4679 }
4680 }
4681 mFocusedDisplayId = displayId;
4682
Chris Ye3c2d6f52020-08-09 10:39:48 -07004683 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004684 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004685 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004686
Vishnu Nairad321cd2020-08-20 16:40:21 -07004687 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004688 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004689 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004690 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004691 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004692 }
4693 }
4694 }
4695
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004696 if (DEBUG_FOCUS) {
4697 logDispatchStateLocked();
4698 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004699 } // release lock
4700
4701 // Wake up poll loop since it may need to make new input dispatching choices.
4702 mLooper->wake();
4703}
4704
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004706 if (DEBUG_FOCUS) {
4707 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709
4710 bool changed;
4711 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004712 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713
4714 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4715 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004716 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 }
4718
4719 if (mDispatchEnabled && !enabled) {
4720 resetAndDropEverythingLocked("dispatcher is being disabled");
4721 }
4722
4723 mDispatchEnabled = enabled;
4724 mDispatchFrozen = frozen;
4725 changed = true;
4726 } else {
4727 changed = false;
4728 }
4729
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004730 if (DEBUG_FOCUS) {
4731 logDispatchStateLocked();
4732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 } // release lock
4734
4735 if (changed) {
4736 // Wake up poll loop since it may need to make new input dispatching choices.
4737 mLooper->wake();
4738 }
4739}
4740
4741void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004742 if (DEBUG_FOCUS) {
4743 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745
4746 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004747 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748
4749 if (mInputFilterEnabled == enabled) {
4750 return;
4751 }
4752
4753 mInputFilterEnabled = enabled;
4754 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4755 } // release lock
4756
4757 // Wake up poll loop since there might be work to do to drop everything.
4758 mLooper->wake();
4759}
4760
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004761void InputDispatcher::setInTouchMode(bool inTouchMode) {
4762 std::scoped_lock lock(mLock);
4763 mInTouchMode = inTouchMode;
4764}
4765
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004766void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4767 if (opacity < 0 || opacity > 1) {
4768 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4769 return;
4770 }
4771
4772 std::scoped_lock lock(mLock);
4773 mMaximumObscuringOpacityForTouch = opacity;
4774}
4775
4776void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4777 std::scoped_lock lock(mLock);
4778 mBlockUntrustedTouchesMode = mode;
4779}
4780
arthurhungb89ccb02020-12-30 16:19:01 +08004781bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4782 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004783 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004784 if (DEBUG_FOCUS) {
4785 ALOGD("Trivial transfer to same window.");
4786 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004787 return true;
4788 }
4789
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004791 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792
chaviwfbe5d9c2018-12-26 12:23:37 -08004793 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4794 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004795 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004796 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 return false;
4798 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004799 if (DEBUG_FOCUS) {
4800 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4801 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004804 if (DEBUG_FOCUS) {
4805 ALOGD("Cannot transfer focus because windows are on different displays.");
4806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 return false;
4808 }
4809
4810 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004811 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4812 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004813 for (size_t i = 0; i < state.windows.size(); i++) {
4814 const TouchedWindow& touchedWindow = state.windows[i];
4815 if (touchedWindow.windowHandle == fromWindowHandle) {
4816 int32_t oldTargetFlags = touchedWindow.targetFlags;
4817 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004819 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004821 int32_t newTargetFlags = oldTargetFlags &
4822 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4823 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004824 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825
arthurhungb89ccb02020-12-30 16:19:01 +08004826 // Store the dragging window.
4827 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004828 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004829 }
4830
Jeff Brownf086ddb2014-02-11 14:28:48 -08004831 found = true;
4832 goto Found;
4833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 }
4835 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004836 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004838 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004839 if (DEBUG_FOCUS) {
4840 ALOGD("Focus transfer failed because from window did not have focus.");
4841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 return false;
4843 }
4844
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004845 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4846 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004847 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004848 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 CancelationOptions
4850 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4851 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004853 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 }
4855
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004856 if (DEBUG_FOCUS) {
4857 logDispatchStateLocked();
4858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 } // release lock
4860
4861 // Wake up poll loop since it may need to make new input dispatching choices.
4862 mLooper->wake();
4863 return true;
4864}
4865
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004866// Binder call
4867bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4868 sp<IBinder> fromToken;
4869 { // acquire lock
4870 std::scoped_lock _l(mLock);
4871
4872 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4873 if (toWindowHandle == nullptr) {
4874 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4875 return false;
4876 }
4877
4878 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4879
4880 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4881 if (touchStateIt == mTouchStatesByDisplay.end()) {
4882 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4883 displayId);
4884 return false;
4885 }
4886
4887 TouchState& state = touchStateIt->second;
4888 if (state.windows.size() != 1) {
4889 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4890 state.windows.size());
4891 return false;
4892 }
4893 const TouchedWindow& touchedWindow = state.windows[0];
4894 fromToken = touchedWindow.windowHandle->getToken();
4895 } // release lock
4896
4897 return transferTouchFocus(fromToken, destChannelToken);
4898}
4899
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004901 if (DEBUG_FOCUS) {
4902 ALOGD("Resetting and dropping all events (%s).", reason);
4903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904
4905 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4906 synthesizeCancelationEventsForAllConnectionsLocked(options);
4907
4908 resetKeyRepeatLocked();
4909 releasePendingEventLocked();
4910 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004911 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004914 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004916 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917}
4918
4919void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004920 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 dumpDispatchStateLocked(dump);
4922
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004923 std::istringstream stream(dump);
4924 std::string line;
4925
4926 while (std::getline(stream, line, '\n')) {
4927 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929}
4930
Prabir Pradhan99987712020-11-10 18:43:05 -08004931std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4932 std::string dump;
4933
4934 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4935 toString(mFocusedWindowRequestedPointerCapture));
4936
4937 std::string windowName = "None";
4938 if (mWindowTokenWithPointerCapture) {
4939 const sp<InputWindowHandle> captureWindowHandle =
4940 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4941 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4942 : "token has capture without window";
4943 }
4944 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4945
4946 return dump;
4947}
4948
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004949void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004950 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4951 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4952 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004953 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954
Tiger Huang721e26f2018-07-24 22:26:19 +08004955 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4956 dump += StringPrintf(INDENT "FocusedApplications:\n");
4957 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4958 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004959 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004960 const std::chrono::duration timeout =
4961 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004962 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004963 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004964 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004967 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004969
Vishnu Nairc519ff72021-01-21 08:23:08 -08004970 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004971 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004973 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004974 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004975 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4976 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004977 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004978 state.displayId, toString(state.down), toString(state.split),
4979 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004980 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004981 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004982 for (size_t i = 0; i < state.windows.size(); i++) {
4983 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 dump += StringPrintf(INDENT4
4985 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4986 i, touchedWindow.windowHandle->getName().c_str(),
4987 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004988 }
4989 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004990 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004991 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004992 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004993 dump += INDENT3 "Portal windows:\n";
4994 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004995 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004996 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4997 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004998 }
4999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 }
5001 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005002 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 }
5004
arthurhung6d4bed92021-03-17 11:59:33 +08005005 if (mDragState) {
5006 dump += StringPrintf(INDENT "DragState:\n");
5007 mDragState->dump(dump, INDENT2);
5008 }
5009
Arthur Hungb92218b2018-08-14 12:00:21 +08005010 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005011 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005012 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005013 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005014 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005015 dump += INDENT2 "Windows:\n";
5016 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005017 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08005018 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005020 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005021 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005022 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005023 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005024 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005025 "applicationInfo.name=%s, "
5026 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005027 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005028 i, windowInfo->name.c_str(), windowInfo->id,
5029 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005030 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005031 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005032 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005033 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005034 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005035 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005036 windowInfo->frameLeft, windowInfo->frameTop,
5037 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005038 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005039 windowInfo->applicationInfo.name.c_str(),
5040 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005041 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005042 dump += StringPrintf(", inputFeatures=%s",
5043 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005044 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005045 "ms, trustedOverlay=%s, hasToken=%s, "
5046 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005047 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005048 millis(windowInfo->dispatchingTimeout),
5049 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005050 toString(windowInfo->token != nullptr),
5051 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005052 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005053 }
5054 } else {
5055 dump += INDENT2 "Windows: <none>\n";
5056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 }
5058 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005059 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
5061
Michael Wright3dd60e22019-03-27 22:06:44 +00005062 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005064 const std::vector<Monitor>& monitors = it.second;
5065 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5066 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005067 }
5068 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005069 const std::vector<Monitor>& monitors = it.second;
5070 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5071 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005074 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 }
5076
5077 nsecs_t currentTime = now();
5078
5079 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005080 if (!mRecentQueue.empty()) {
5081 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005082 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005083 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005084 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005085 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005088 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 }
5090
5091 // Dump event currently being dispatched.
5092 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005093 dump += INDENT "PendingEvent:\n";
5094 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005095 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005096 dump += StringPrintf(", age=%" PRId64 "ms\n",
5097 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101
5102 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005103 if (!mInboundQueue.empty()) {
5104 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005105 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005107 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005108 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 }
5110 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005111 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005114 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005115 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005116 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5117 const KeyReplacement& replacement = pair.first;
5118 int32_t newKeyCode = pair.second;
5119 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005120 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005121 }
5122 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005123 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005124 }
5125
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005126 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005127 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005128 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005129 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005130 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005131 connection->inputChannel->getFd().get(),
5132 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005133 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005134 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005136 if (!connection->outboundQueue.empty()) {
5137 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5138 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005139 dump += dumpQueue(connection->outboundQueue, currentTime);
5140
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005142 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
5144
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005145 if (!connection->waitQueue.empty()) {
5146 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5147 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005148 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005150 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 }
5152 }
5153 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005154 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 }
5156
5157 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005158 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5159 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005161 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005164 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005165 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5166 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5167 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005168 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005169 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170}
5171
Michael Wright3dd60e22019-03-27 22:06:44 +00005172void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5173 const size_t numMonitors = monitors.size();
5174 for (size_t i = 0; i < numMonitors; i++) {
5175 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005176 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005177 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5178 dump += "\n";
5179 }
5180}
5181
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005182class LooperEventCallback : public LooperCallback {
5183public:
5184 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5185 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5186
5187private:
5188 std::function<int(int events)> mCallback;
5189};
5190
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005191Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005192#if DEBUG_CHANNEL_CREATION
5193 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194#endif
5195
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005196 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005197 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005198 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005199
5200 if (result) {
5201 return base::Error(result) << "Failed to open input channel pair with name " << name;
5202 }
5203
Michael Wrightd02c5b62014-02-10 15:10:22 -08005204 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005205 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005206 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005207 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005208 sp<Connection> connection =
5209 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005211 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5212 ALOGE("Created a new connection, but the token %p is already known", token.get());
5213 }
5214 mConnectionsByToken.emplace(token, connection);
5215
5216 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5217 this, std::placeholders::_1, token);
5218
5219 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 } // release lock
5221
5222 // Wake the looper because some connections have changed.
5223 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005224 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225}
5226
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005227Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5228 bool isGestureMonitor,
5229 const std::string& name,
5230 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005231 std::shared_ptr<InputChannel> serverChannel;
5232 std::unique_ptr<InputChannel> clientChannel;
5233 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5234 if (result) {
5235 return base::Error(result) << "Failed to open input channel pair with name " << name;
5236 }
5237
Michael Wright3dd60e22019-03-27 22:06:44 +00005238 { // acquire lock
5239 std::scoped_lock _l(mLock);
5240
5241 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005242 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5243 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005244 }
5245
Garfield Tan15601662020-09-22 15:32:38 -07005246 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005247 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005248 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005249
5250 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5251 ALOGE("Created a new connection, but the token %p is already known", token.get());
5252 }
5253 mConnectionsByToken.emplace(token, connection);
5254 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5255 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005256
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257 auto& monitorsByDisplay =
5258 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005259 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005260
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005261 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005262 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5263 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005264 }
Garfield Tan15601662020-09-22 15:32:38 -07005265
Michael Wright3dd60e22019-03-27 22:06:44 +00005266 // Wake the looper because some connections have changed.
5267 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005268 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005269}
5270
Garfield Tan15601662020-09-22 15:32:38 -07005271status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005273 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274
Garfield Tan15601662020-09-22 15:32:38 -07005275 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 if (status) {
5277 return status;
5278 }
5279 } // release lock
5280
5281 // Wake the poll loop because removing the connection may have changed the current
5282 // synchronization state.
5283 mLooper->wake();
5284 return OK;
5285}
5286
Garfield Tan15601662020-09-22 15:32:38 -07005287status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5288 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005289 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005290 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005291 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292 return BAD_VALUE;
5293 }
5294
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005295 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005296
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005298 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 }
5300
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005301 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302
5303 nsecs_t currentTime = now();
5304 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5305
5306 connection->status = Connection::STATUS_ZOMBIE;
5307 return OK;
5308}
5309
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005310void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5311 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5312 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005313}
5314
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005315void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005316 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005317 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005318 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005319 std::vector<Monitor>& monitors = it->second;
5320 const size_t numMonitors = monitors.size();
5321 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005322 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005323 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5324 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005325 monitors.erase(monitors.begin() + i);
5326 break;
5327 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005328 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005329 if (monitors.empty()) {
5330 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005331 } else {
5332 ++it;
5333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 }
5335}
5336
Michael Wright3dd60e22019-03-27 22:06:44 +00005337status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5338 { // acquire lock
5339 std::scoped_lock _l(mLock);
5340 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5341
5342 if (!foundDisplayId) {
5343 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5344 return BAD_VALUE;
5345 }
5346 int32_t displayId = foundDisplayId.value();
5347
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005348 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5349 mTouchStatesByDisplay.find(displayId);
5350 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005351 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5352 return BAD_VALUE;
5353 }
5354
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005355 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005356 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005357 std::optional<int32_t> foundDeviceId;
5358 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005359 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005360 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005361 foundDeviceId = state.deviceId;
5362 }
5363 }
5364 if (!foundDeviceId || !state.down) {
5365 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005366 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005367 return BAD_VALUE;
5368 }
5369 int32_t deviceId = foundDeviceId.value();
5370
5371 // Send cancel events to all the input channels we're stealing from.
5372 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005373 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005374 options.deviceId = deviceId;
5375 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005376 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005377 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005378 std::shared_ptr<InputChannel> channel =
5379 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005380 if (channel != nullptr) {
5381 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005382 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005383 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005384 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005385 canceledWindows += "]";
5386 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5387 canceledWindows.c_str());
5388
Michael Wright3dd60e22019-03-27 22:06:44 +00005389 // Then clear the current touch state so we stop dispatching to them as well.
5390 state.filterNonMonitors();
5391 }
5392 return OK;
5393}
5394
Prabir Pradhan99987712020-11-10 18:43:05 -08005395void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5396 { // acquire lock
5397 std::scoped_lock _l(mLock);
5398 if (DEBUG_FOCUS) {
5399 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5400 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5401 windowHandle != nullptr ? windowHandle->getName().c_str()
5402 : "token without window");
5403 }
5404
Vishnu Nairc519ff72021-01-21 08:23:08 -08005405 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005406 if (focusedToken != windowToken) {
5407 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5408 enabled ? "enable" : "disable");
5409 return;
5410 }
5411
5412 if (enabled == mFocusedWindowRequestedPointerCapture) {
5413 ALOGW("Ignoring request to %s Pointer Capture: "
5414 "window has %s requested pointer capture.",
5415 enabled ? "enable" : "disable", enabled ? "already" : "not");
5416 return;
5417 }
5418
5419 mFocusedWindowRequestedPointerCapture = enabled;
5420 setPointerCaptureLocked(enabled);
5421 } // release lock
5422
5423 // Wake the thread to process command entries.
5424 mLooper->wake();
5425}
5426
Michael Wright3dd60e22019-03-27 22:06:44 +00005427std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5428 const sp<IBinder>& token) {
5429 for (const auto& it : mGestureMonitorsByDisplay) {
5430 const std::vector<Monitor>& monitors = it.second;
5431 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005432 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005433 return it.first;
5434 }
5435 }
5436 }
5437 return std::nullopt;
5438}
5439
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005440std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5441 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5442 if (gesturePid.has_value()) {
5443 return gesturePid;
5444 }
5445 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5446}
5447
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005448sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005449 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005450 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005451 }
5452
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005453 for (const auto& [token, connection] : mConnectionsByToken) {
5454 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005455 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 }
5457 }
Robert Carr4e670e52018-08-15 13:26:12 -07005458
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005459 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460}
5461
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005462std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5463 sp<Connection> connection = getConnectionLocked(connectionToken);
5464 if (connection == nullptr) {
5465 return "<nullptr>";
5466 }
5467 return connection->getInputChannelName();
5468}
5469
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005470void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005471 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005472 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005473}
5474
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005475void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5476 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005477 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005478 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5479 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 commandEntry->connection = connection;
5481 commandEntry->eventTime = currentTime;
5482 commandEntry->seq = seq;
5483 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005484 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005485 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486}
5487
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005488void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5489 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005491 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005493 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5494 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005496 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497}
5498
Vishnu Nairad321cd2020-08-20 16:40:21 -07005499void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5500 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005501 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5502 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005503 commandEntry->oldToken = oldToken;
5504 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005505 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005506}
5507
arthurhungf452d0b2021-01-06 00:19:52 +08005508void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5509 std::unique_ptr<CommandEntry> commandEntry =
5510 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5511 commandEntry->newToken = token;
5512 commandEntry->x = x;
5513 commandEntry->y = y;
5514 postCommandLocked(std::move(commandEntry));
5515}
5516
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005517void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5518 if (connection == nullptr) {
5519 LOG_ALWAYS_FATAL("Caller must check for nullness");
5520 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005521 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5522 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005523 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005524 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005525 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005526 return;
5527 }
5528 /**
5529 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5530 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5531 * has changed. This could cause newer entries to time out before the already dispatched
5532 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5533 * processes the events linearly. So providing information about the oldest entry seems to be
5534 * most useful.
5535 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005536 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005537 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5538 std::string reason =
5539 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005540 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005541 ns2ms(currentWait),
5542 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005543 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005544 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005545
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005546 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5547
5548 // Stop waking up for events on this connection, it is already unresponsive
5549 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005550}
5551
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005552void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5553 std::string reason =
5554 StringPrintf("%s does not have a focused window", application->getName().c_str());
5555 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005556
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005557 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5558 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5559 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005560 postCommandLocked(std::move(commandEntry));
5561}
5562
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005563void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5564 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5565 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5566 commandEntry->obscuringPackage = obscuringPackage;
5567 postCommandLocked(std::move(commandEntry));
5568}
5569
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005570void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5571 const std::string& reason) {
5572 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5573 updateLastAnrStateLocked(windowLabel, reason);
5574}
5575
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005576void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5577 const std::string& reason) {
5578 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005579 updateLastAnrStateLocked(windowLabel, reason);
5580}
5581
5582void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5583 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005585 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 struct tm tm;
5587 localtime_r(&t, &tm);
5588 char timestr[64];
5589 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005590 mLastAnrState.clear();
5591 mLastAnrState += INDENT "ANR:\n";
5592 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005593 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5594 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005595 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596}
5597
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005598void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599 mLock.unlock();
5600
5601 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5602
5603 mLock.lock();
5604}
5605
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005606void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 sp<Connection> connection = commandEntry->connection;
5608
5609 if (connection->status != Connection::STATUS_ZOMBIE) {
5610 mLock.unlock();
5611
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005612 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613
5614 mLock.lock();
5615 }
5616}
5617
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005618void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005619 sp<IBinder> oldToken = commandEntry->oldToken;
5620 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005621 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005622 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005623 mLock.lock();
5624}
5625
arthurhungf452d0b2021-01-06 00:19:52 +08005626void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5627 sp<IBinder> newToken = commandEntry->newToken;
5628 mLock.unlock();
5629 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5630 mLock.lock();
5631}
5632
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005633void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005635
5636 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5637
5638 mLock.lock();
5639}
5640
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005641void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005642 mLock.unlock();
5643
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005644 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645
5646 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005647}
5648
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005649void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005650 mLock.unlock();
5651
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005652 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5653
5654 mLock.lock();
5655}
5656
5657void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5658 mLock.unlock();
5659
5660 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5661
5662 mLock.lock();
5663}
5664
5665void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5666 mLock.unlock();
5667
5668 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005669
5670 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005671}
5672
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005673void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5674 mLock.unlock();
5675
5676 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5677
5678 mLock.lock();
5679}
5680
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5682 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005683 KeyEntry& entry = *(commandEntry->keyEntry);
5684 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685
5686 mLock.unlock();
5687
Michael Wright2b3c3302018-03-02 17:19:13 +00005688 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005689 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005690 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005691 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5692 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005693 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695
5696 mLock.lock();
5697
5698 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005699 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005701 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005703 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5704 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706}
5707
chaviwfd6d3512019-03-25 13:23:49 -07005708void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5709 mLock.unlock();
5710 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5711 mLock.lock();
5712}
5713
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005714/**
5715 * Connection is responsive if it has no events in the waitQueue that are older than the
5716 * current time.
5717 */
5718static bool isConnectionResponsive(const Connection& connection) {
5719 const nsecs_t currentTime = now();
5720 for (const DispatchEntry* entry : connection.waitQueue) {
5721 if (entry->timeoutTime < currentTime) {
5722 return false;
5723 }
5724 }
5725 return true;
5726}
5727
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005728void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005730 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005732 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733
5734 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005735 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005736 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005737 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005739 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005740 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005741 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005742 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5743 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005744 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005745 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5746 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5747 connection->inputChannel->getConnectionToken(),
5748 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5749 finishTime);
5750 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005751
5752 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005753 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005754 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005755 restartEvent =
5756 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005757 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005758 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005759 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5760 handled);
5761 } else {
5762 restartEvent = false;
5763 }
5764
5765 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005766 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005767 // contents of the wait queue to have been drained, so we need to double-check
5768 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005769 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5770 if (dispatchEntryIt != connection->waitQueue.end()) {
5771 dispatchEntry = *dispatchEntryIt;
5772 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005773 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5774 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005775 if (!connection->responsive) {
5776 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005777 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005778 // The connection was unresponsive, and now it's responsive.
5779 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005780 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005781 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005782 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005783 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005784 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005785 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005786 } else {
5787 releaseDispatchEntry(dispatchEntry);
5788 }
5789 }
5790
5791 // Start the next dispatch cycle for this connection.
5792 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793}
5794
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005795void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5796 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5797 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5798 monitorUnresponsiveCommand->pid = pid;
5799 monitorUnresponsiveCommand->reason = std::move(reason);
5800 postCommandLocked(std::move(monitorUnresponsiveCommand));
5801}
5802
5803void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5804 std::string reason) {
5805 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5806 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5807 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5808 windowUnresponsiveCommand->reason = std::move(reason);
5809 postCommandLocked(std::move(windowUnresponsiveCommand));
5810}
5811
5812void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5813 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5814 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5815 monitorResponsiveCommand->pid = pid;
5816 postCommandLocked(std::move(monitorResponsiveCommand));
5817}
5818
5819void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5820 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5821 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5822 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5823 postCommandLocked(std::move(windowResponsiveCommand));
5824}
5825
5826/**
5827 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5828 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5829 * command entry to the command queue.
5830 */
5831void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5832 std::string reason) {
5833 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5834 if (connection.monitor) {
5835 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5836 reason.c_str());
5837 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5838 if (!pid.has_value()) {
5839 ALOGE("Could not find unresponsive monitor for connection %s",
5840 connection.inputChannel->getName().c_str());
5841 return;
5842 }
5843 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5844 return;
5845 }
5846 // If not a monitor, must be a window
5847 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5848 reason.c_str());
5849 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5850}
5851
5852/**
5853 * Tell the policy that a connection has become responsive so that it can stop ANR.
5854 */
5855void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5856 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5857 if (connection.monitor) {
5858 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5859 if (!pid.has_value()) {
5860 ALOGE("Could not find responsive monitor for connection %s",
5861 connection.inputChannel->getName().c_str());
5862 return;
5863 }
5864 sendMonitorResponsiveCommandLocked(pid.value());
5865 return;
5866 }
5867 // If not a monitor, must be a window
5868 sendWindowResponsiveCommandLocked(connectionToken);
5869}
5870
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005872 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005873 KeyEntry& keyEntry, bool handled) {
5874 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005875 if (!handled) {
5876 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005877 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005878 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005879 return false;
5880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005882 // Get the fallback key state.
5883 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005884 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005885 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005886 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005887 connection->inputState.removeFallbackKey(originalKeyCode);
5888 }
5889
5890 if (handled || !dispatchEntry->hasForegroundTarget()) {
5891 // If the application handles the original key for which we previously
5892 // generated a fallback or if the window is not a foreground window,
5893 // then cancel the associated fallback key, if any.
5894 if (fallbackKeyCode != -1) {
5895 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005898 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005899 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005901 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005902 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903
5904 mLock.unlock();
5905
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005906 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005907 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908
5909 mLock.lock();
5910
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005911 // Cancel the fallback key.
5912 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005914 "application handled the original non-fallback key "
5915 "or is no longer a foreground target, "
5916 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917 options.keyCode = fallbackKeyCode;
5918 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005920 connection->inputState.removeFallbackKey(originalKeyCode);
5921 }
5922 } else {
5923 // If the application did not handle a non-fallback key, first check
5924 // that we are in a good state to perform unhandled key event processing
5925 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005926 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005927 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005929 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005930 "since this is not an initial down. "
5931 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005934 return false;
5935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005937 // Dispatch the unhandled key to the policy.
5938#if DEBUG_OUTBOUND_EVENT_DETAILS
5939 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005940 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005941 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005942#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005943 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005944
5945 mLock.unlock();
5946
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005947 bool fallback =
5948 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005949 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005950
5951 mLock.lock();
5952
5953 if (connection->status != Connection::STATUS_NORMAL) {
5954 connection->inputState.removeFallbackKey(originalKeyCode);
5955 return false;
5956 }
5957
5958 // Latch the fallback keycode for this key on an initial down.
5959 // The fallback keycode cannot change at any other point in the lifecycle.
5960 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005962 fallbackKeyCode = event.getKeyCode();
5963 } else {
5964 fallbackKeyCode = AKEYCODE_UNKNOWN;
5965 }
5966 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5967 }
5968
5969 ALOG_ASSERT(fallbackKeyCode != -1);
5970
5971 // Cancel the fallback key if the policy decides not to send it anymore.
5972 // We will continue to dispatch the key to the policy but we will no
5973 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005974 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5975 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976#if DEBUG_OUTBOUND_EVENT_DETAILS
5977 if (fallback) {
5978 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005979 "as a fallback for %d, but on the DOWN it had requested "
5980 "to send %d instead. Fallback canceled.",
5981 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005982 } else {
5983 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005984 "but on the DOWN it had requested to send %d. "
5985 "Fallback canceled.",
5986 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005987 }
5988#endif
5989
5990 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5991 "canceling fallback, policy no longer desires it");
5992 options.keyCode = fallbackKeyCode;
5993 synthesizeCancelationEventsForConnectionLocked(connection, options);
5994
5995 fallback = false;
5996 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005997 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005998 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005999 }
6000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006001
6002#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006003 {
6004 std::string msg;
6005 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6006 connection->inputState.getFallbackKeys();
6007 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006008 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006011 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006012 }
6013#endif
6014
6015 if (fallback) {
6016 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006017 keyEntry.eventTime = event.getEventTime();
6018 keyEntry.deviceId = event.getDeviceId();
6019 keyEntry.source = event.getSource();
6020 keyEntry.displayId = event.getDisplayId();
6021 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6022 keyEntry.keyCode = fallbackKeyCode;
6023 keyEntry.scanCode = event.getScanCode();
6024 keyEntry.metaState = event.getMetaState();
6025 keyEntry.repeatCount = event.getRepeatCount();
6026 keyEntry.downTime = event.getDownTime();
6027 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006028
6029#if DEBUG_OUTBOUND_EVENT_DETAILS
6030 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006031 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006032 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006033#endif
6034 return true; // restart the event
6035 } else {
6036#if DEBUG_OUTBOUND_EVENT_DETAILS
6037 ALOGD("Unhandled key event: No fallback key.");
6038#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006039
6040 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042 }
6043 }
6044 return false;
6045}
6046
6047bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006048 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006049 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 return false;
6051}
6052
6053void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6054 mLock.unlock();
6055
Sean Stoutb4e0a592021-02-23 07:34:53 -08006056 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6057 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006058
6059 mLock.lock();
6060}
6061
Michael Wrightd02c5b62014-02-10 15:10:22 -08006062void InputDispatcher::traceInboundQueueLengthLocked() {
6063 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006064 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065 }
6066}
6067
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006068void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069 if (ATRACE_ENABLED()) {
6070 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006071 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6072 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073 }
6074}
6075
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006076void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006077 if (ATRACE_ENABLED()) {
6078 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006079 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6080 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 }
6082}
6083
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006084void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006085 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006087 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 dumpDispatchStateLocked(dump);
6089
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006090 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006091 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006092 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093 }
6094}
6095
6096void InputDispatcher::monitor() {
6097 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006098 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006100 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101}
6102
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006103/**
6104 * Wake up the dispatcher and wait until it processes all events and commands.
6105 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6106 * this method can be safely called from any thread, as long as you've ensured that
6107 * the work you are interested in completing has already been queued.
6108 */
6109bool InputDispatcher::waitForIdle() {
6110 /**
6111 * Timeout should represent the longest possible time that a device might spend processing
6112 * events and commands.
6113 */
6114 constexpr std::chrono::duration TIMEOUT = 100ms;
6115 std::unique_lock lock(mLock);
6116 mLooper->wake();
6117 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6118 return result == std::cv_status::no_timeout;
6119}
6120
Vishnu Naire798b472020-07-23 13:52:21 -07006121/**
6122 * Sets focus to the window identified by the token. This must be called
6123 * after updating any input window handles.
6124 *
6125 * Params:
6126 * request.token - input channel token used to identify the window that should gain focus.
6127 * request.focusedToken - the token that the caller expects currently to be focused. If the
6128 * specified token does not match the currently focused window, this request will be dropped.
6129 * If the specified focused token matches the currently focused window, the call will succeed.
6130 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6131 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6132 * when requesting the focus change. This determines which request gets
6133 * precedence if there is a focus change request from another source such as pointer down.
6134 */
Vishnu Nair958da932020-08-21 17:12:37 -07006135void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6136 { // acquire lock
6137 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006138 std::optional<FocusResolver::FocusChanges> changes =
6139 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6140 if (changes) {
6141 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006142 }
6143 } // release lock
6144 // Wake up poll loop since it may need to make new input dispatching choices.
6145 mLooper->wake();
6146}
6147
Vishnu Nairc519ff72021-01-21 08:23:08 -08006148void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6149 if (changes.oldFocus) {
6150 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006151 if (focusedInputChannel) {
6152 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6153 "focus left window");
6154 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006155 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006156 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006157 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006158 if (changes.newFocus) {
6159 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006160 }
6161
Prabir Pradhan99987712020-11-10 18:43:05 -08006162 // If a window has pointer capture, then it must have focus. We need to ensure that this
6163 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6164 // If the window loses focus before it loses pointer capture, then the window can be in a state
6165 // where it has pointer capture but not focus, violating the contract. Therefore we must
6166 // dispatch the pointer capture event before the focus event. Since focus events are added to
6167 // the front of the queue (above), we add the pointer capture event to the front of the queue
6168 // after the focus events are added. This ensures the pointer capture event ends up at the
6169 // front.
6170 disablePointerCaptureForcedLocked();
6171
Vishnu Nairc519ff72021-01-21 08:23:08 -08006172 if (mFocusedDisplayId == changes.displayId) {
6173 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006174 }
6175}
Vishnu Nair958da932020-08-21 17:12:37 -07006176
Prabir Pradhan99987712020-11-10 18:43:05 -08006177void InputDispatcher::disablePointerCaptureForcedLocked() {
6178 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6179 return;
6180 }
6181
6182 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6183
6184 if (mFocusedWindowRequestedPointerCapture) {
6185 mFocusedWindowRequestedPointerCapture = false;
6186 setPointerCaptureLocked(false);
6187 }
6188
6189 if (!mWindowTokenWithPointerCapture) {
6190 // No need to send capture changes because no window has capture.
6191 return;
6192 }
6193
6194 if (mPendingEvent != nullptr) {
6195 // Move the pending event to the front of the queue. This will give the chance
6196 // for the pending event to be dropped if it is a captured event.
6197 mInboundQueue.push_front(mPendingEvent);
6198 mPendingEvent = nullptr;
6199 }
6200
6201 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6202 false /* hasCapture */);
6203 mInboundQueue.push_front(std::move(entry));
6204}
6205
Prabir Pradhan99987712020-11-10 18:43:05 -08006206void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6207 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6208 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6209 commandEntry->enabled = enabled;
6210 postCommandLocked(std::move(commandEntry));
6211}
6212
6213void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6214 android::inputdispatcher::CommandEntry* commandEntry) {
6215 mLock.unlock();
6216
6217 mPolicy->setPointerCapture(commandEntry->enabled);
6218
6219 mLock.lock();
6220}
6221
Vishnu Nair599f1412021-06-21 10:39:58 -07006222void InputDispatcher::displayRemoved(int32_t displayId) {
6223 { // acquire lock
6224 std::scoped_lock _l(mLock);
6225 // Set an empty list to remove all handles from the specific display.
6226 setInputWindowsLocked(/* window handles */ {}, displayId);
6227 setFocusedApplicationLocked(displayId, nullptr);
6228 // Call focus resolver to clean up stale requests. This must be called after input windows
6229 // have been removed for the removed display.
6230 mFocusResolver.displayRemoved(displayId);
6231 } // release lock
6232
6233 // Wake up poll loop since it may need to make new input dispatching choices.
6234 mLooper->wake();
6235}
6236
Garfield Tane84e6f92019-08-29 17:28:41 -07006237} // namespace android::inputdispatcher