blob: 7b7c42a211999fcf6ef3d957e58b1f65a1f7f196 [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
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070028#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050029#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080031#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080032#include <input/PrintTools.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070033#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010034#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080036
Michael Wright44753b12020-07-08 13:48:11 +010037#include <cerrno>
38#include <cinttypes>
39#include <climits>
40#include <cstddef>
41#include <ctime>
42#include <queue>
43#include <sstream>
44
45#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000046#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070047#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#define INDENT " "
50#define INDENT2 " "
51#define INDENT3 " "
52#define INDENT4 " "
53
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080054using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080055using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000056using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070058using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050059using android::gui::FocusRequest;
60using android::gui::TouchOcclusionMode;
61using android::gui::WindowInfo;
62using android::gui::WindowInfoHandle;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100063using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080064using android::os::InputEventInjectionResult;
65using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066
Garfield Tane84e6f92019-08-29 17:28:41 -070067namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080068
Prabir Pradhancef936d2021-07-21 16:17:52 +000069namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000070// Temporarily releases a held mutex for the lifetime of the instance.
71// Named to match std::scoped_lock
72class scoped_unlock {
73public:
74 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
75 ~scoped_unlock() { mMutex.lock(); }
76
77private:
78 std::mutex& mMutex;
79};
80
Michael Wrightd02c5b62014-02-10 15:10:22 -080081// Default input dispatching timeout if there is no focused application or paused window
82// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080083const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
84 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
85 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
87// Amount of time to allow for all pending events to be processed when an app switch
88// key is on the way. This is used to preempt input dispatch and drop input events
89// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080092const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// 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 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Antonio Kantekea47acb2021-12-23 12:41:25 -0800108// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000111constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000113inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114 return systemTime(SYSTEM_TIME_MONOTONIC);
115}
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118 return value ? "true" : "false";
119}
120
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000121inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000122 if (binder == nullptr) {
123 return "<null>";
124 }
125 return StringPrintf("%p", binder.get());
126}
127
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000128inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700129 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
130 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131}
132
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000133bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700135 case AKEY_EVENT_ACTION_DOWN:
136 case AKEY_EVENT_ACTION_UP:
137 return true;
138 default:
139 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 }
141}
142
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000143bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 ALOGE("Key event has invalid action code 0x%x", action);
146 return false;
147 }
148 return true;
149}
150
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000151bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 case AMOTION_EVENT_ACTION_DOWN:
154 case AMOTION_EVENT_ACTION_UP:
155 case AMOTION_EVENT_ACTION_CANCEL:
156 case AMOTION_EVENT_ACTION_MOVE:
157 case AMOTION_EVENT_ACTION_OUTSIDE:
158 case AMOTION_EVENT_ACTION_HOVER_ENTER:
159 case AMOTION_EVENT_ACTION_HOVER_MOVE:
160 case AMOTION_EVENT_ACTION_HOVER_EXIT:
161 case AMOTION_EVENT_ACTION_SCROLL:
162 return true;
163 case AMOTION_EVENT_ACTION_POINTER_DOWN:
164 case AMOTION_EVENT_ACTION_POINTER_UP: {
165 int32_t index = getMotionEventActionPointerIndex(action);
166 return index >= 0 && index < pointerCount;
167 }
168 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
169 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
170 return actionButton != 0;
171 default:
172 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173 }
174}
175
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000176int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500177 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
178}
179
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000180bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
181 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700182 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183 ALOGE("Motion event has invalid action code 0x%x", action);
184 return false;
185 }
186 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800187 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700188 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 BitSet32 pointerIdBits;
192 for (size_t i = 0; i < pointerCount; i++) {
193 int32_t id = pointerProperties[i].id;
194 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700195 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
196 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 return false;
198 }
199 if (pointerIdBits.hasBit(id)) {
200 ALOGE("Motion event has duplicate pointer id %d", id);
201 return false;
202 }
203 pointerIdBits.markBit(id);
204 }
205 return true;
206}
207
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000208std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000210 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000213 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 bool first = true;
215 Region::const_iterator cur = region.begin();
216 Region::const_iterator const tail = region.end();
217 while (cur != tail) {
218 if (first) {
219 first = false;
220 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 cur++;
225 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000226 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227}
228
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000229std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500230 constexpr size_t maxEntries = 50; // max events to print
231 constexpr size_t skipBegin = maxEntries / 2;
232 const size_t skipEnd = queue.size() - maxEntries / 2;
233 // skip from maxEntries / 2 ... size() - maxEntries/2
234 // only print from 0 .. skipBegin and then from skipEnd .. size()
235
236 std::string dump;
237 for (size_t i = 0; i < queue.size(); i++) {
238 const DispatchEntry& entry = *queue[i];
239 if (i >= skipBegin && i < skipEnd) {
240 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
241 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
242 continue;
243 }
244 dump.append(INDENT4);
245 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800246 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
247 "ms",
248 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500249 ns2ms(currentTime - entry.eventEntry->eventTime));
250 if (entry.deliveryTime != 0) {
251 // This entry was delivered, so add information on how long we've been waiting
252 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
253 }
254 dump.append("\n");
255 }
256 return dump;
257}
258
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700259/**
260 * Find the entry in std::unordered_map by key, and return it.
261 * If the entry is not found, return a default constructed entry.
262 *
263 * Useful when the entries are vectors, since an empty vector will be returned
264 * if the entry is not found.
265 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
266 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700267template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000268V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700269 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700270 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800271}
272
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000273bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700274 if (first == second) {
275 return true;
276 }
277
278 if (first == nullptr || second == nullptr) {
279 return false;
280 }
281
282 return first->getToken() == second->getToken();
283}
284
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000285bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000286 if (first == nullptr || second == nullptr) {
287 return false;
288 }
289 return first->applicationInfo.token != nullptr &&
290 first->applicationInfo.token == second->applicationInfo.token;
291}
292
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800293std::unique_ptr<DispatchEntry> createDispatchEntry(
294 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
295 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700296 if (inputTarget.useDefaultPointerTransform()) {
297 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700298 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700299 inputTarget.displayTransform,
300 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000301 }
302
303 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
304 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
305
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700306 std::vector<PointerCoords> pointerCoords;
307 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000308
309 // Use the first pointer information to normalize all other pointers. This could be any pointer
310 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700311 // uses the transform for the normalized pointer.
312 const ui::Transform& firstPointerTransform =
313 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
314 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000315
316 // Iterate through all pointers in the event to normalize against the first.
317 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
318 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
319 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700320 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321
322 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700323 // First, apply the current pointer's transform to update the coordinates into
324 // window space.
325 pointerCoords[pointerIndex].transform(currTransform);
326 // Next, apply the inverse transform of the normalized coordinates so the
327 // current coordinates are transformed into the normalized coordinate space.
328 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000329 }
330
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700331 std::unique_ptr<MotionEntry> combinedMotionEntry =
332 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
333 motionEntry.deviceId, motionEntry.source,
334 motionEntry.displayId, motionEntry.policyFlags,
335 motionEntry.action, motionEntry.actionButton,
336 motionEntry.flags, motionEntry.metaState,
337 motionEntry.buttonState, motionEntry.classification,
338 motionEntry.edgeFlags, motionEntry.xPrecision,
339 motionEntry.yPrecision, motionEntry.xCursorPosition,
340 motionEntry.yCursorPosition, motionEntry.downTime,
341 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000342 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000343
344 if (motionEntry.injectionState) {
345 combinedMotionEntry->injectionState = motionEntry.injectionState;
346 combinedMotionEntry->injectionState->refCount += 1;
347 }
348
349 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700350 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700351 firstPointerTransform, inputTarget.displayTransform,
352 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000353 return dispatchEntry;
354}
355
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000356status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
357 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700358 std::unique_ptr<InputChannel> uniqueServerChannel;
359 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
360
361 serverChannel = std::move(uniqueServerChannel);
362 return result;
363}
364
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500365template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000366bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500367 if (lhs == nullptr && rhs == nullptr) {
368 return true;
369 }
370 if (lhs == nullptr || rhs == nullptr) {
371 return false;
372 }
373 return *lhs == *rhs;
374}
375
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000376KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000377 KeyEvent event;
378 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
379 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
380 entry.repeatCount, entry.downTime, entry.eventTime);
381 return event;
382}
383
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000384bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000385 // Do not keep track of gesture monitors. They receive every event and would disproportionately
386 // affect the statistics.
387 if (connection.monitor) {
388 return false;
389 }
390 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
391 if (!connection.responsive) {
392 return false;
393 }
394 return true;
395}
396
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000397bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000398 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
399 const int32_t& inputEventId = eventEntry.id;
400 if (inputEventId != dispatchEntry.resolvedEventId) {
401 // Event was transmuted
402 return false;
403 }
404 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
405 return false;
406 }
407 // Only track latency for events that originated from hardware
408 if (eventEntry.isSynthesized()) {
409 return false;
410 }
411 const EventEntry::Type& inputEventEntryType = eventEntry.type;
412 if (inputEventEntryType == EventEntry::Type::KEY) {
413 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
414 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
415 return false;
416 }
417 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
418 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
419 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
420 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
421 return false;
422 }
423 } else {
424 // Not a key or a motion
425 return false;
426 }
427 if (!shouldReportMetricsForConnection(connection)) {
428 return false;
429 }
430 return true;
431}
432
Prabir Pradhancef936d2021-07-21 16:17:52 +0000433/**
434 * Connection is responsive if it has no events in the waitQueue that are older than the
435 * current time.
436 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000437bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000438 const nsecs_t currentTime = now();
439 for (const DispatchEntry* entry : connection.waitQueue) {
440 if (entry->timeoutTime < currentTime) {
441 return false;
442 }
443 }
444 return true;
445}
446
Antonio Kantekf16f2832021-09-28 04:39:20 +0000447// Returns true if the event type passed as argument represents a user activity.
448bool isUserActivityEvent(const EventEntry& eventEntry) {
449 switch (eventEntry.type) {
450 case EventEntry::Type::FOCUS:
451 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
452 case EventEntry::Type::DRAG:
453 case EventEntry::Type::TOUCH_MODE_CHANGED:
454 case EventEntry::Type::SENSOR:
455 case EventEntry::Type::CONFIGURATION_CHANGED:
456 return false;
457 case EventEntry::Type::DEVICE_RESET:
458 case EventEntry::Type::KEY:
459 case EventEntry::Type::MOTION:
460 return true;
461 }
462}
463
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800464// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700465bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
466 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800467 const auto inputConfig = windowInfo.inputConfig;
468 if (windowInfo.displayId != displayId ||
469 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800470 return false;
471 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700472 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800473 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800474 return false;
475 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800476 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800477 return false;
478 }
479 return true;
480}
481
Prabir Pradhand65552b2021-10-07 11:23:50 -0700482bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
483 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
484 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
485 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
486}
487
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800488// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000489// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
490// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
491// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800492// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000493bool canReceiveForegroundTouches(const WindowInfo& info) {
494 // A non-touchable window can still receive touch events (e.g. in the case of
495 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
496 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
497}
498
Antonio Kantek48710e42022-03-24 14:19:30 -0700499bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
500 if (windowHandle == nullptr) {
501 return false;
502 }
503 const WindowInfo* windowInfo = windowHandle->getInfo();
504 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
505 return true;
506 }
507 return false;
508}
509
Prabir Pradhan5735a322022-04-11 17:23:34 +0000510// Checks targeted injection using the window's owner's uid.
511// Returns an empty string if an entry can be sent to the given window, or an error message if the
512// entry is a targeted injection whose uid target doesn't match the window owner.
513std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
514 const EventEntry& entry) {
515 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
516 // The event was not injected, or the injected event does not target a window.
517 return {};
518 }
519 const int32_t uid = *entry.injectionState->targetUid;
520 if (window == nullptr) {
521 return StringPrintf("No valid window target for injection into uid %d.", uid);
522 }
523 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
524 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
525 "owned by uid %d.",
526 uid, window->getName().c_str(), window->getInfo()->ownerUid);
527 }
528 return {};
529}
530
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700531Point resolveTouchedPosition(const MotionEntry& entry) {
532 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
533 // Always dispatch mouse events to cursor position.
534 if (isFromMouse) {
535 return Point(static_cast<int32_t>(entry.xCursorPosition),
536 static_cast<int32_t>(entry.yCursorPosition));
537 }
538
539 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
540 return Point(static_cast<int32_t>(
541 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
542 static_cast<int32_t>(
543 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
544}
545
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700546std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
547 if (eventEntry.type == EventEntry::Type::KEY) {
548 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
549 return keyEntry.downTime;
550 } else if (eventEntry.type == EventEntry::Type::MOTION) {
551 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
552 return motionEntry.downTime;
553 }
554 return std::nullopt;
555}
556
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000557} // namespace
558
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559// --- InputDispatcher ---
560
Garfield Tan00f511d2019-06-12 16:55:40 -0700561InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800562 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
563
564InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
565 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700566 : mPolicy(policy),
567 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700568 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800569 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700570 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700571 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700572 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800573 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700574 mDispatchEnabled(false),
575 mDispatchFrozen(false),
576 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100577 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000578 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800579 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800580 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000581 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000582 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700583 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800584 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700586 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700587#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700588 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700589#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700590 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 policy->getDispatcherConfiguration(&mConfig);
592}
593
594InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000595 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596
Prabir Pradhancef936d2021-07-21 16:17:52 +0000597 resetKeyRepeatLocked();
598 releasePendingEventLocked();
599 drainInboundQueueLocked();
600 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000602 while (!mConnectionsByToken.empty()) {
603 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000604 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
605 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 }
607}
608
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700609status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700610 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700611 return ALREADY_EXISTS;
612 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700613 mThread = std::make_unique<InputThread>(
614 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
615 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700616}
617
618status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700619 if (mThread && mThread->isCallingThread()) {
620 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700621 return INVALID_OPERATION;
622 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700623 mThread.reset();
624 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700625}
626
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700628 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800630 std::scoped_lock _l(mLock);
631 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632
633 // Run a dispatch loop if there are no pending commands.
634 // The dispatch loop might enqueue commands to run afterwards.
635 if (!haveCommandsLocked()) {
636 dispatchOnceInnerLocked(&nextWakeupTime);
637 }
638
639 // Run all pending commands if there are any.
640 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000641 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700642 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800644
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700645 // If we are still waiting for ack on some events,
646 // we might have to wake up earlier to check if an app is anr'ing.
647 const nsecs_t nextAnrCheck = processAnrsLocked();
648 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
649
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800650 // We are about to enter an infinitely long sleep, because we have no commands or
651 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700652 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800653 mDispatcherEnteredIdle.notify_all();
654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 } // release lock
656
657 // Wait for callback or timeout or wake. (make sure we round up, not down)
658 nsecs_t currentTime = now();
659 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
660 mLooper->pollOnce(timeoutMillis);
661}
662
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700663/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500664 * Raise ANR if there is no focused window.
665 * Before the ANR is raised, do a final state check:
666 * 1. The currently focused application must be the same one we are waiting for.
667 * 2. Ensure we still don't have a focused window.
668 */
669void InputDispatcher::processNoFocusedWindowAnrLocked() {
670 // Check if the application that we are waiting for is still focused.
671 std::shared_ptr<InputApplicationHandle> focusedApplication =
672 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
673 if (focusedApplication == nullptr ||
674 focusedApplication->getApplicationToken() !=
675 mAwaitedFocusedApplication->getApplicationToken()) {
676 // Unexpected because we should have reset the ANR timer when focused application changed
677 ALOGE("Waited for a focused window, but focused application has already changed to %s",
678 focusedApplication->getName().c_str());
679 return; // The focused application has changed.
680 }
681
chaviw98318de2021-05-19 16:45:23 -0500682 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500683 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
684 if (focusedWindowHandle != nullptr) {
685 return; // We now have a focused window. No need for ANR.
686 }
687 onAnrLocked(mAwaitedFocusedApplication);
688}
689
690/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691 * Check if any of the connections' wait queues have events that are too old.
692 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
693 * Return the time at which we should wake up next.
694 */
695nsecs_t InputDispatcher::processAnrsLocked() {
696 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700697 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700698 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
699 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
700 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500701 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700702 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500703 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700704 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500706 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
708 }
709 }
710
711 // Check if any connection ANRs are due
712 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
713 if (currentTime < nextAnrCheck) { // most likely scenario
714 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
715 }
716
717 // If we reached here, we have an unresponsive connection.
718 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
719 if (connection == nullptr) {
720 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
721 return nextAnrCheck;
722 }
723 connection->responsive = false;
724 // Stop waking up for this unresponsive connection
725 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000726 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700727 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700728}
729
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800730std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
731 const sp<Connection>& connection) {
732 if (connection->monitor) {
733 return mMonitorDispatchingTimeout;
734 }
735 const sp<WindowInfoHandle> window =
736 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700737 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500738 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700739 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500740 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700741}
742
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
744 nsecs_t currentTime = now();
745
Jeff Browndc5992e2014-04-11 01:27:26 -0700746 // Reset the key repeat timer whenever normal dispatch is suspended while the
747 // device is in a non-interactive state. This is to ensure that we abort a key
748 // repeat if the device is just coming out of sleep.
749 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 resetKeyRepeatLocked();
751 }
752
753 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
754 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100755 if (DEBUG_FOCUS) {
756 ALOGD("Dispatch frozen. Waiting some more.");
757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 return;
759 }
760
761 // Optimize latency of app switches.
762 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
763 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
764 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
765 if (mAppSwitchDueTime < *nextWakeupTime) {
766 *nextWakeupTime = mAppSwitchDueTime;
767 }
768
769 // Ready to start a new event.
770 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700772 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 if (isAppSwitchDue) {
774 // The inbound queue is empty so the app switch key we were waiting
775 // for will never arrive. Stop waiting for it.
776 resetPendingAppSwitchLocked(false);
777 isAppSwitchDue = false;
778 }
779
780 // Synthesize a key repeat if appropriate.
781 if (mKeyRepeatState.lastKeyEntry) {
782 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
783 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
784 } else {
785 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
786 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
787 }
788 }
789 }
790
791 // Nothing to do if there is no pending event.
792 if (!mPendingEvent) {
793 return;
794 }
795 } else {
796 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700797 mPendingEvent = mInboundQueue.front();
798 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 traceInboundQueueLengthLocked();
800 }
801
802 // Poke user activity for this event.
803 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700804 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807
808 // Now we have an event to dispatch.
809 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700810 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700812 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700814 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 }
818
819 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700820 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
822
823 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700824 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700825 const ConfigurationChangedEntry& typedEntry =
826 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700828 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829 break;
830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700832 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700833 const DeviceResetEntry& typedEntry =
834 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700836 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700837 break;
838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100840 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700841 std::shared_ptr<FocusEntry> typedEntry =
842 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100843 dispatchFocusLocked(currentTime, typedEntry);
844 done = true;
845 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
846 break;
847 }
848
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700849 case EventEntry::Type::TOUCH_MODE_CHANGED: {
850 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
851 dispatchTouchModeChangeLocked(currentTime, typedEntry);
852 done = true;
853 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
854 break;
855 }
856
Prabir Pradhan99987712020-11-10 18:43:05 -0800857 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
858 const auto typedEntry =
859 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
860 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
861 done = true;
862 break;
863 }
864
arthurhungb89ccb02020-12-30 16:19:01 +0800865 case EventEntry::Type::DRAG: {
866 std::shared_ptr<DragEntry> typedEntry =
867 std::static_pointer_cast<DragEntry>(mPendingEvent);
868 dispatchDragLocked(currentTime, typedEntry);
869 done = true;
870 break;
871 }
872
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700873 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 resetPendingAppSwitchLocked(true);
878 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 } else if (dropReason == DropReason::NOT_DROPPED) {
880 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 }
882 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700883 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700886 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
887 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700889 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 break;
891 }
892
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700893 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700894 std::shared_ptr<MotionEntry> motionEntry =
895 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700896 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
897 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700899 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
903 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700905 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
Chris Yef59a2f42020-10-16 12:55:26 -0700908
909 case EventEntry::Type::SENSOR: {
910 std::shared_ptr<SensorEntry> sensorEntry =
911 std::static_pointer_cast<SensorEntry>(mPendingEvent);
912 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
913 dropReason = DropReason::APP_SWITCH;
914 }
915 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
916 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
917 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
918 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
919 dropReason = DropReason::STALE;
920 }
921 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
922 done = true;
923 break;
924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
926
927 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700928 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
Michael Wright3a981722015-06-10 15:26:13 +0100931 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932
933 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700934 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 }
936}
937
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800938bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
939 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
940}
941
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700942/**
943 * Return true if the events preceding this incoming motion event should be dropped
944 * Return false otherwise (the default behaviour)
945 */
946bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700948 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949
950 // Optimize case where the current application is unresponsive and the user
951 // decides to touch a window in a different application.
952 // If the application takes too long to catch up then we drop all events preceding
953 // the touch into the other window.
954 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700955 const int32_t displayId = motionEntry.displayId;
956 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700957 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700958
chaviw98318de2021-05-19 16:45:23 -0500959 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700960 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700962 touchedWindowHandle->getApplicationToken() !=
963 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700964 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700965 ALOGI("Pruning input queue because user touched a different application while waiting "
966 "for %s",
967 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700968 return true;
969 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700970
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800971 // Alternatively, maybe there's a spy window that could handle this event.
972 const std::vector<sp<WindowInfoHandle>> touchedSpies =
973 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
974 for (const auto& windowHandle : touchedSpies) {
975 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000976 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800977 // This spy window could take more input. Drop all events preceding this
978 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700979 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800980 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700981 mAwaitedFocusedApplication->getName().c_str());
982 return true;
983 }
984 }
985 }
986
987 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
988 // yet been processed by some connections, the dispatcher will wait for these motion
989 // events to be processed before dispatching the key event. This is because these motion events
990 // may cause a new window to be launched, which the user might expect to receive focus.
991 // To prevent waiting forever for such events, just send the key to the currently focused window
992 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
993 ALOGD("Received a new pointer down event, stop waiting for events to process and "
994 "just send the pending key event to the focused window.");
995 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700996 }
997 return false;
998}
999
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001000bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001001 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001002 mInboundQueue.push_back(std::move(newEntry));
1003 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 traceInboundQueueLengthLocked();
1005
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001006 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001007 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001008 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1009 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 // Optimize app switch latency.
1011 // If the application takes too long to catch up then we drop all events preceding
1012 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001013 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001014 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001015 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001017 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001019 if (DEBUG_APP_SWITCH) {
1020 ALOGD("App switch is pending!");
1021 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001022 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001023 mAppSwitchSawKeyDown = false;
1024 needWake = true;
1025 }
1026 }
1027 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001028
1029 // If a new up event comes in, and the pending event with same key code has been asked
1030 // to try again later because of the policy. We have to reset the intercept key wake up
1031 // time for it may have been handled in the policy and could be dropped.
1032 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1033 mPendingEvent->type == EventEntry::Type::KEY) {
1034 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1035 if (pendingKey.keyCode == keyEntry.keyCode &&
1036 pendingKey.interceptKeyResult ==
1037 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1038 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1039 pendingKey.interceptKeyWakeupTime = 0;
1040 needWake = true;
1041 }
1042 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 break;
1044 }
1045
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001046 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001047 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1048 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001049 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1050 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001051 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001055 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001056 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1057 break;
1058 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001059 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001060 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001061 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001062 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001063 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1064 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 // nothing to do
1066 break;
1067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069
1070 return needWake;
1071}
1072
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001073void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001074 // Do not store sensor event in recent queue to avoid flooding the queue.
1075 if (entry->type != EventEntry::Type::SENSOR) {
1076 mRecentQueue.push_back(entry);
1077 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001078 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001079 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
1081}
1082
chaviw98318de2021-05-19 16:45:23 -05001083sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1084 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001085 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001086 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001087 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001088 if (addOutsideTargets && touchState == nullptr) {
1089 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001092 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001093 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001094 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001095 continue;
1096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001098 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001099 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001100 return windowHandle;
1101 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001102
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001103 if (addOutsideTargets &&
1104 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001105 touchState->addOrUpdateWindow(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001106 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 }
1108 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001109 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110}
1111
Prabir Pradhand65552b2021-10-07 11:23:50 -07001112std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1113 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001114 // Traverse windows from front to back and gather the touched spy windows.
1115 std::vector<sp<WindowInfoHandle>> spyWindows;
1116 const auto& windowHandles = getWindowHandlesLocked(displayId);
1117 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1118 const WindowInfo& info = *windowHandle->getInfo();
1119
Prabir Pradhand65552b2021-10-07 11:23:50 -07001120 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001121 continue;
1122 }
1123 if (!info.isSpy()) {
1124 // The first touched non-spy window was found, so return the spy windows touched so far.
1125 return spyWindows;
1126 }
1127 spyWindows.push_back(windowHandle);
1128 }
1129 return spyWindows;
1130}
1131
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001132void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 const char* reason;
1134 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001136 if (DEBUG_INBOUND_EVENT_DETAILS) {
1137 ALOGD("Dropped event because policy consumed it.");
1138 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 reason = "inbound event was dropped because the policy consumed it";
1140 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001141 case DropReason::DISABLED:
1142 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 ALOGI("Dropped event because input dispatch is disabled.");
1144 }
1145 reason = "inbound event was dropped because input dispatch is disabled";
1146 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001147 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 ALOGI("Dropped event because of pending overdue app switch.");
1149 reason = "inbound event was dropped because of pending overdue app switch";
1150 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001151 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 ALOGI("Dropped event because the current application is not responding and the user "
1153 "has started interacting with a different application.");
1154 reason = "inbound event was dropped because the current application is not responding "
1155 "and the user has started interacting with a different application";
1156 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001157 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 ALOGI("Dropped event because it is stale.");
1159 reason = "inbound event was dropped because it is stale";
1160 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001161 case DropReason::NO_POINTER_CAPTURE:
1162 ALOGI("Dropped event because there is no window with Pointer Capture.");
1163 reason = "inbound event was dropped because there is no window with Pointer Capture";
1164 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001165 case DropReason::NOT_DROPPED: {
1166 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001172 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1174 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001177 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001178 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1179 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1181 synthesizeCancelationEventsForAllConnectionsLocked(options);
1182 } else {
1183 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1184 synthesizeCancelationEventsForAllConnectionsLocked(options);
1185 }
1186 break;
1187 }
Chris Yef59a2f42020-10-16 12:55:26 -07001188 case EventEntry::Type::SENSOR: {
1189 break;
1190 }
arthurhungb89ccb02020-12-30 16:19:01 +08001191 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1192 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001193 break;
1194 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001195 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001196 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001197 case EventEntry::Type::CONFIGURATION_CHANGED:
1198 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001199 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001200 break;
1201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
1203}
1204
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001205static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1207 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208}
1209
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001210bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1211 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1212 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1213 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214}
1215
1216bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001217 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218}
1219
1220void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001221 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001223 if (DEBUG_APP_SWITCH) {
1224 if (handled) {
1225 ALOGD("App switch has arrived.");
1226 } else {
1227 ALOGD("App switch was abandoned.");
1228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230}
1231
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001233 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234}
1235
Prabir Pradhancef936d2021-07-21 16:17:52 +00001236bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001237 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 return false;
1239 }
1240
1241 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001242 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001243 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001244 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1245 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001246 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 return true;
1248}
1249
Prabir Pradhancef936d2021-07-21 16:17:52 +00001250void InputDispatcher::postCommandLocked(Command&& command) {
1251 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252}
1253
1254void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001255 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001256 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001257 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 releaseInboundEventLocked(entry);
1259 }
1260 traceInboundQueueLengthLocked();
1261}
1262
1263void InputDispatcher::releasePendingEventLocked() {
1264 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001266 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268}
1269
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001270void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001272 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001273 if (DEBUG_DISPATCH_CYCLE) {
1274 ALOGD("Injected inbound event was dropped.");
1275 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001276 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001279 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 }
1281 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282}
1283
1284void InputDispatcher::resetKeyRepeatLocked() {
1285 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001286 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 }
1288}
1289
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1291 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292
Michael Wright2e732952014-09-24 13:26:59 -07001293 uint32_t policyFlags = entry->policyFlags &
1294 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001296 std::shared_ptr<KeyEntry> newEntry =
1297 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1298 entry->source, entry->displayId, policyFlags, entry->action,
1299 entry->flags, entry->keyCode, entry->scanCode,
1300 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001302 newEntry->syntheticRepeat = true;
1303 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306}
1307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001309 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001310 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1311 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313
1314 // Reset key repeating in case a keyboard device was added or removed or something.
1315 resetKeyRepeatLocked();
1316
1317 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001318 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1319 scoped_unlock unlock(mLock);
1320 mPolicy->notifyConfigurationChanged(eventTime);
1321 };
1322 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 return true;
1324}
1325
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001326bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1327 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001328 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1329 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1330 entry.deviceId);
1331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332
liushenxiang42232912021-05-21 20:24:09 +08001333 // Reset key repeating in case a keyboard device was disabled or enabled.
1334 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1335 resetKeyRepeatLocked();
1336 }
1337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001339 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 synthesizeCancelationEventsForAllConnectionsLocked(options);
1341 return true;
1342}
1343
Vishnu Nairad321cd2020-08-20 16:40:21 -07001344void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001345 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001346 if (mPendingEvent != nullptr) {
1347 // Move the pending event to the front of the queue. This will give the chance
1348 // for the pending event to get dispatched to the newly focused window
1349 mInboundQueue.push_front(mPendingEvent);
1350 mPendingEvent = nullptr;
1351 }
1352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001353 std::unique_ptr<FocusEntry> focusEntry =
1354 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1355 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001356
1357 // This event should go to the front of the queue, but behind all other focus events
1358 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001359 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001360 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 [](const std::shared_ptr<EventEntry>& event) {
1362 return event->type == EventEntry::Type::FOCUS;
1363 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001364
1365 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001366 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001367}
1368
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001369void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001370 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001371 if (channel == nullptr) {
1372 return; // Window has gone away
1373 }
1374 InputTarget target;
1375 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001376 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001377 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001378 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1379 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001380 std::string reason = std::string("reason=").append(entry->reason);
1381 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001382 dispatchEventLocked(currentTime, entry, {target});
1383}
1384
Prabir Pradhan99987712020-11-10 18:43:05 -08001385void InputDispatcher::dispatchPointerCaptureChangedLocked(
1386 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1387 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001388 dropReason = DropReason::NOT_DROPPED;
1389
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001392
1393 if (entry->pointerCaptureRequest.enable) {
1394 // Enable Pointer Capture.
1395 if (haveWindowWithPointerCapture &&
1396 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001397 // This can happen if pointer capture is disabled and re-enabled before we notify the
1398 // app of the state change, so there is no need to notify the app.
1399 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1400 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001401 }
1402 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001403 // This can happen if a window requests capture and immediately releases capture.
1404 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001405 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001406 return;
1407 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001408 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1409 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1410 return;
1411 }
1412
Vishnu Nairc519ff72021-01-21 08:23:08 -08001413 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001414 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1415 mWindowTokenWithPointerCapture = token;
1416 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001417 // Disable Pointer Capture.
1418 // We do not check if the sequence number matches for requests to disable Pointer Capture
1419 // for two reasons:
1420 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1421 // to disable capture with the same sequence number: one generated by
1422 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1423 // Capture being disabled in InputReader.
1424 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1425 // actual Pointer Capture state that affects events being generated by input devices is
1426 // in InputReader.
1427 if (!haveWindowWithPointerCapture) {
1428 // Pointer capture was already forcefully disabled because of focus change.
1429 dropReason = DropReason::NOT_DROPPED;
1430 return;
1431 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001432 token = mWindowTokenWithPointerCapture;
1433 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001434 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001435 setPointerCaptureLocked(false);
1436 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001437 }
1438
1439 auto channel = getInputChannelLocked(token);
1440 if (channel == nullptr) {
1441 // Window has gone away, clean up Pointer Capture state.
1442 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001443 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001444 setPointerCaptureLocked(false);
1445 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001446 return;
1447 }
1448 InputTarget target;
1449 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001450 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001451 entry->dispatchInProgress = true;
1452 dispatchEventLocked(currentTime, entry, {target});
1453
1454 dropReason = DropReason::NOT_DROPPED;
1455}
1456
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001457void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1458 const std::shared_ptr<TouchModeEntry>& entry) {
1459 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001460 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001461 if (windowHandles.empty()) {
1462 return;
1463 }
1464 const std::vector<InputTarget> inputTargets =
1465 getInputTargetsFromWindowHandlesLocked(windowHandles);
1466 if (inputTargets.empty()) {
1467 return;
1468 }
1469 entry->dispatchInProgress = true;
1470 dispatchEventLocked(currentTime, entry, inputTargets);
1471}
1472
1473std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1474 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1475 std::vector<InputTarget> inputTargets;
1476 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001477 const sp<IBinder>& token = handle->getToken();
1478 if (token == nullptr) {
1479 continue;
1480 }
1481 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1482 if (channel == nullptr) {
1483 continue; // Window has gone away
1484 }
1485 InputTarget target;
1486 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001487 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001488 inputTargets.push_back(target);
1489 }
1490 return inputTargets;
1491}
1492
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001493bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 if (!entry->dispatchInProgress) {
1497 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1498 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1499 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1500 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001501 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 // We have seen two identical key downs in a row which indicates that the device
1503 // driver is automatically generating key repeats itself. We take note of the
1504 // repeat here, but we disable our own next key repeat timer since it is clear that
1505 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001506 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1507 // Make sure we don't get key down from a different device. If a different
1508 // device Id has same key pressed down, the new device Id will replace the
1509 // current one to hold the key repeat with repeat count reset.
1510 // In the future when got a KEY_UP on the device id, drop it and do not
1511 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1513 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001514 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 } else {
1516 // Not a repeat. Save key down state in case we do see a repeat later.
1517 resetKeyRepeatLocked();
1518 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1519 }
1520 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001521 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1522 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001524 if (DEBUG_INBOUND_EVENT_DETAILS) {
1525 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1526 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001527 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 resetKeyRepeatLocked();
1529 }
1530
1531 if (entry->repeatCount == 1) {
1532 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1533 } else {
1534 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1535 }
1536
1537 entry->dispatchInProgress = true;
1538
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001539 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 }
1541
1542 // Handle case where the policy asked us to try again later last time.
1543 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1544 if (currentTime < entry->interceptKeyWakeupTime) {
1545 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1546 *nextWakeupTime = entry->interceptKeyWakeupTime;
1547 }
1548 return false; // wait until next wakeup
1549 }
1550 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1551 entry->interceptKeyWakeupTime = 0;
1552 }
1553
1554 // Give the policy a chance to intercept the key.
1555 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1556 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001557 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001558 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001559
1560 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1561 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1562 };
1563 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 return false; // wait for the command to run
1565 } else {
1566 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1567 }
1568 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001569 if (*dropReason == DropReason::NOT_DROPPED) {
1570 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 }
1572 }
1573
1574 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001575 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001576 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1578 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001579 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 return true;
1581 }
1582
1583 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001584 InputEventInjectionResult injectionResult;
1585 sp<WindowInfoHandle> focusedWindow =
1586 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1587 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001588 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 return false;
1590 }
1591
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001592 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001593 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 return true;
1595 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001596 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1597
1598 std::vector<InputTarget> inputTargets;
1599 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001600 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001601 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001603 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001604 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605
1606 // Dispatch the key.
1607 dispatchEventLocked(currentTime, entry, inputTargets);
1608 return true;
1609}
1610
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001612 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1613 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1614 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1615 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1616 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1617 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1618 entry.metaState, entry.repeatCount, entry.downTime);
1619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620}
1621
Prabir Pradhancef936d2021-07-21 16:17:52 +00001622void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1623 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001624 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001625 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1626 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1627 "source=0x%x, sensorType=%s",
1628 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001629 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001630 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001631 auto command = [this, entry]() REQUIRES(mLock) {
1632 scoped_unlock unlock(mLock);
1633
1634 if (entry->accuracyChanged) {
1635 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1636 }
1637 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1638 entry->hwTimestamp, entry->values);
1639 };
1640 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001641}
1642
1643bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001644 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1645 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001646 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001647 }
Chris Yef59a2f42020-10-16 12:55:26 -07001648 { // acquire lock
1649 std::scoped_lock _l(mLock);
1650
1651 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1652 std::shared_ptr<EventEntry> entry = *it;
1653 if (entry->type == EventEntry::Type::SENSOR) {
1654 it = mInboundQueue.erase(it);
1655 releaseInboundEventLocked(entry);
1656 }
1657 }
1658 }
1659 return true;
1660}
1661
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001662bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001664 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 entry->dispatchInProgress = true;
1668
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001669 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 }
1671
1672 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001673 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001674 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001675 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1676 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 return true;
1678 }
1679
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001680 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681
1682 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001683 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684
1685 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001686 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 if (isPointerEvent) {
1688 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001689
1690 if (mDragState &&
1691 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1692 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1693 pilferPointersLocked(mDragState->dragWindow->getToken());
1694 }
1695
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001696 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001697 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001698 /*byref*/ injectionResult);
1699 for (const TouchedWindow& touchedWindow : touchedWindows) {
1700 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1701 "Shouldn't be adding window if the injection didn't succeed.");
1702 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1703 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1704 inputTargets);
1705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 } else {
1707 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001708 sp<WindowInfoHandle> focusedWindow =
1709 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1710 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1711 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1712 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001713 InputTarget::Flags::FOREGROUND |
1714 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001715 BitSet32(0), getDownTime(*entry), inputTargets);
1716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001718 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 return false;
1720 }
1721
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001722 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001723 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001724 return true;
1725 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001726 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001727 CancelationOptions::Mode mode(isPointerEvent
1728 ? CancelationOptions::CANCEL_POINTER_EVENTS
1729 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1730 CancelationOptions options(mode, "input event injection failed");
1731 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 return true;
1733 }
1734
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001735 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
1738 // Dispatch the motion.
1739 if (conflictingPointerActions) {
1740 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 synthesizeCancelationEventsForAllConnectionsLocked(options);
1743 }
1744 dispatchEventLocked(currentTime, entry, inputTargets);
1745 return true;
1746}
1747
chaviw98318de2021-05-19 16:45:23 -05001748void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001749 bool isExiting, const int32_t rawX,
1750 const int32_t rawY) {
1751 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001752 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001753 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1754 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001755
1756 enqueueInboundEventLocked(std::move(dragEntry));
1757}
1758
1759void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1760 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1761 if (channel == nullptr) {
1762 return; // Window has gone away
1763 }
1764 InputTarget target;
1765 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001766 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001767 entry->dispatchInProgress = true;
1768 dispatchEventLocked(currentTime, entry, {target});
1769}
1770
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001771void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001772 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1773 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1774 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001775 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001776 "metaState=0x%x, buttonState=0x%x,"
1777 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1778 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001779 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1780 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1781 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001783 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1784 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1785 "x=%f, y=%f, pressure=%f, size=%f, "
1786 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1787 "orientation=%f",
1788 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1796 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1797 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800}
1801
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001802void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1803 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001804 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001805 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001806 if (DEBUG_DISPATCH_CYCLE) {
1807 ALOGD("dispatchEventToCurrentInputTargets");
1808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001810 updateInteractionTokensLocked(*eventEntry, inputTargets);
1811
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1813
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001816 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001817 sp<Connection> connection =
1818 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001819 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001820 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001822 if (DEBUG_FOCUS) {
1823 ALOGD("Dropping event delivery to target with channel '%s' because it "
1824 "is no longer registered with the input dispatcher.",
1825 inputTarget.inputChannel->getName().c_str());
1826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
1828 }
1829}
1830
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1832 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1833 // If the policy decides to close the app, we will get a channel removal event via
1834 // unregisterInputChannel, and will clean up the connection that way. We are already not
1835 // sending new pointers to the connection when it blocked, but focused events will continue to
1836 // pile up.
1837 ALOGW("Canceling events for %s because it is unresponsive",
1838 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001839 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001840 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1841 "application not responding");
1842 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 }
1844}
1845
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001846void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001847 if (DEBUG_FOCUS) {
1848 ALOGD("Resetting ANR timeouts.");
1849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850
1851 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001852 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001853 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854}
1855
Tiger Huang721e26f2018-07-24 22:26:19 +08001856/**
1857 * Get the display id that the given event should go to. If this event specifies a valid display id,
1858 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1859 * Focused display is the display that the user most recently interacted with.
1860 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001862 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001864 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001865 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1866 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001867 break;
1868 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001869 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001870 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1871 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 break;
1873 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001874 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001875 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001876 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001877 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001878 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001879 case EventEntry::Type::SENSOR:
1880 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001881 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001882 return ADISPLAY_ID_NONE;
1883 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001884 }
1885 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1886}
1887
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001888bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1889 const char* focusedWindowName) {
1890 if (mAnrTracker.empty()) {
1891 // already processed all events that we waited for
1892 mKeyIsWaitingForEventsTimeout = std::nullopt;
1893 return false;
1894 }
1895
1896 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1897 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001898 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001899 mKeyIsWaitingForEventsTimeout = currentTime +
1900 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1901 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 return true;
1903 }
1904
1905 // We still have pending events, and already started the timer
1906 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1907 return true; // Still waiting
1908 }
1909
1910 // Waited too long, and some connection still hasn't processed all motions
1911 // Just send the key to the focused window
1912 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1913 focusedWindowName);
1914 mKeyIsWaitingForEventsTimeout = std::nullopt;
1915 return false;
1916}
1917
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001918sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1919 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1920 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001921 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001922 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923
Tiger Huang721e26f2018-07-24 22:26:19 +08001924 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001925 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001926 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001927 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1928
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 // If there is no currently focused window and no focused application
1930 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1932 ALOGI("Dropping %s event because there is no focused window or focused application in "
1933 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001934 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001935 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
1937
Vishnu Nair062a8672021-09-03 16:07:44 -07001938 // Drop key events if requested by input feature
1939 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001940 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001941 }
1942
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001943 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1944 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1945 // start interacting with another application via touch (app switch). This code can be removed
1946 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1947 // an app is expected to have a focused window.
1948 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1949 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1950 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001951 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1952 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1953 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001954 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001955 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 ALOGW("Waiting because no window has focus but %s may eventually add a "
1957 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001958 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001959 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001960 outInjectionResult = InputEventInjectionResult::PENDING;
1961 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1963 // Already raised ANR. Drop the event
1964 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001965 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001966 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001967 } else {
1968 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001969 outInjectionResult = InputEventInjectionResult::PENDING;
1970 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001971 }
1972 }
1973
1974 // we have a valid, non-null focused window
1975 resetNoFocusedWindowTimeoutLocked();
1976
Prabir Pradhan5735a322022-04-11 17:23:34 +00001977 // Verify targeted injection.
1978 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1979 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001980 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1981 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
1983
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001984 if (focusedWindowHandle->getInfo()->inputConfig.test(
1985 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001987 outInjectionResult = InputEventInjectionResult::PENDING;
1988 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 }
1990
1991 // If the event is a key event, then we must wait for all previous events to
1992 // complete before delivering it because previous events may have the
1993 // side-effect of transferring focus to a different window and we want to
1994 // ensure that the following keys are sent to the new window.
1995 //
1996 // Suppose the user touches a button in a window then immediately presses "A".
1997 // If the button causes a pop-up window to appear then we want to ensure that
1998 // the "A" key is delivered to the new pop-up window. This is because users
1999 // often anticipate pending UI changes when typing on a keyboard.
2000 // To obtain this behavior, we must serialize key events with respect to all
2001 // prior input events.
2002 if (entry.type == EventEntry::Type::KEY) {
2003 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2004 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002005 outInjectionResult = InputEventInjectionResult::PENDING;
2006 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002010 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2011 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012}
2013
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014/**
2015 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2016 * that are currently unresponsive.
2017 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002018std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2019 const std::vector<Monitor>& monitors) const {
2020 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002022 [this](const Monitor& monitor) REQUIRES(mLock) {
2023 sp<Connection> connection =
2024 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 if (connection == nullptr) {
2026 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002027 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 return false;
2029 }
2030 if (!connection->responsive) {
2031 ALOGW("Unresponsive monitor %s will not get the new gesture",
2032 connection->inputChannel->getName().c_str());
2033 return false;
2034 }
2035 return true;
2036 });
2037 return responsiveMonitors;
2038}
2039
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002040/**
2041 * In general, touch should be always split between windows. Some exceptions:
2042 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2043 * from the same device, *and* the window that's receiving the current pointer does not support
2044 * split touch.
2045 * 2. Don't split mouse events
2046 */
2047bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2048 const MotionEntry& entry) const {
2049 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2050 // We should never split mouse events
2051 return false;
2052 }
2053 for (const TouchedWindow& touchedWindow : touchState.windows) {
2054 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2055 // Spy windows should not affect whether or not touch is split.
2056 continue;
2057 }
2058 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2059 continue;
2060 }
2061 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2062 // being sent there. For now, use deviceId from touch state.
2063 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2064 return false;
2065 }
2066 }
2067 return true;
2068}
2069
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002070std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002071 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2072 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002073 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002075 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 // For security reasons, we defer updating the touch state until we are sure that
2077 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002078 const int32_t displayId = entry.displayId;
2079 const int32_t action = entry.action;
2080 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
2082 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002083 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002084 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2085 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 // Copy current touch state into tempTouchState.
2088 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2089 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002090 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002091 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002092 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2093 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002094 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002095 }
2096
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002097 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002098 const bool switchedDevice = (oldState != nullptr) &&
2099 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002100
2101 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2102 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2103 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2104 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2105 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002106 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 if (newGesture) {
2108 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002109 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002110 ALOGI("Dropping event because a pointer for a different device is already down "
2111 "in display %" PRId32,
2112 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002113 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002114 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002115 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002117 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 tempTouchState.deviceId = entry.deviceId;
2119 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002121 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002122 ALOGI("Dropping move event because a pointer for a different device is already active "
2123 "in display %" PRId32,
2124 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002125 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002126 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002127 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 }
2129
2130 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2131 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002132 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002133 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002134 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002135 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002136 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002137 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002138
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002140 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002141 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2142 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002144 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002145 }
2146
Prabir Pradhan5735a322022-04-11 17:23:34 +00002147 // Verify targeted injection.
2148 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2149 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002150 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002151 newTouchedWindowHandle = nullptr;
2152 goto Failed;
2153 }
2154
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002155 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002156 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2158 // New window supports splitting, but we should never split mouse events.
2159 isSplit = !isFromMouse;
2160 } else if (isSplit) {
2161 // New window does not support splitting but we have already split events.
2162 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163 newTouchedWindowHandle = nullptr;
2164 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165 } else {
2166 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002167 // be delivered to a new window which supports split touch. Pointers from a mouse device
2168 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002169 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 }
2171
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002172 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002173 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002174 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2175 newHoverWindowHandle = nullptr;
2176 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002177 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002178 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179 }
2180
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002181 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002182 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002184 // Process the foreground window first so that it is the first to receive the event.
2185 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186 }
2187
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002188 if (newTouchedWindows.empty()) {
2189 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2190 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002191 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002192 goto Failed;
2193 }
2194
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002195 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002196 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002197 continue;
2198 }
2199
2200 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002201 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002202
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002203 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2204 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002205 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002206 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002207
2208 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002209 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002210 }
2211 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002212 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002213 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002214 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002215 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002216
2217 // Update the temporary touch state.
2218 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002219 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002220
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002221 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2222 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002224
2225 // If any existing window is pilfering pointers from newly added window, remove it
2226 BitSet32 canceledPointers = BitSet32(0);
2227 for (const TouchedWindow& window : tempTouchState.windows) {
2228 if (window.isPilferingPointers) {
2229 canceledPointers |= window.pointerIds;
2230 }
2231 }
2232 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 } else {
2234 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2235
2236 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002237 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002238 ALOGD_IF(DEBUG_FOCUS,
2239 "Dropping event because the pointer is not down or we previously "
2240 "dropped the pointer down event in display %" PRId32 ": %s",
2241 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002242 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 goto Failed;
2244 }
2245
arthurhung6d4bed92021-03-17 11:59:33 +08002246 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002247
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002249 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002251 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002252 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002253 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002254 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002255 newTouchedWindowHandle =
2256 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002257
Prabir Pradhan5735a322022-04-11 17:23:34 +00002258 // Verify targeted injection.
2259 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2260 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002261 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002262 newTouchedWindowHandle = nullptr;
2263 goto Failed;
2264 }
2265
Vishnu Nair062a8672021-09-03 16:07:44 -07002266 // Drop touch events if requested by input feature
2267 if (newTouchedWindowHandle != nullptr &&
2268 shouldDropInput(entry, newTouchedWindowHandle)) {
2269 newTouchedWindowHandle = nullptr;
2270 }
2271
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2273 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002274 if (DEBUG_FOCUS) {
2275 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2276 oldTouchedWindowHandle->getName().c_str(),
2277 newTouchedWindowHandle->getName().c_str(), displayId);
2278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002281 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002282 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283
2284 // Make a slippery entrance into the new window.
2285 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002286 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
2288
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002289 ftl::Flags<InputTarget::Flags> targetFlags =
2290 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002291 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002292 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002295 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002298 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002299 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002300 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
2303 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002304 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002305 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2306 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308 }
2309 }
2310
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002311 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002313 // Let the previous window know that the hover sequence is over, unless we already did
2314 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002315 if (mLastHoverWindowHandle != nullptr &&
2316 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2317 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002318 if (DEBUG_HOVER) {
2319 ALOGD("Sending hover exit event to window %s.",
2320 mLastHoverWindowHandle->getName().c_str());
2321 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002323 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2324 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326
Garfield Tandf26e862020-07-01 20:18:19 -07002327 // Let the new window know that the hover sequence is starting, unless we already did it
2328 // when dispatching it as is to newTouchedWindowHandle.
2329 if (newHoverWindowHandle != nullptr &&
2330 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2331 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002332 if (DEBUG_HOVER) {
2333 ALOGD("Sending hover enter event to window %s.",
2334 newHoverWindowHandle->getName().c_str());
2335 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002337 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002338 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340 }
2341
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002342 // Ensure that we have at least one foreground window or at least one window that cannot be a
2343 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2344 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2345 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002346 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2347 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002348 return !canReceiveForegroundTouches(
2349 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002350 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002351 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002352 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2353 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002354 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002355 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
Prabir Pradhan5735a322022-04-11 17:23:34 +00002358 // Ensure that all touched windows are valid for injection.
2359 if (entry.injectionState != nullptr) {
2360 std::string errs;
2361 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002362 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002363 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2364 // dispatched to any uid, since the coords will be zeroed out later.
2365 continue;
2366 }
2367 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2368 if (err) errs += "\n - " + *err;
2369 }
2370 if (!errs.empty()) {
2371 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2372 "%d:%s",
2373 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002374 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002375 goto Failed;
2376 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002378
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 // Check whether windows listening for outside touches are owned by the same UID. If it is
2380 // set the policy flag that we will not reveal coordinate information to this window.
2381 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002382 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002383 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002384 if (foregroundWindowHandle) {
2385 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002386 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002387 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002388 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2389 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2390 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002391 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002392 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395 }
2396 }
2397 }
2398
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 // If this is the first pointer going down and the touched window has a wallpaper
2400 // then also add the touched wallpaper windows so they are locked in for the duration
2401 // of the touch gesture.
2402 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2403 // engine only supports touch events. We would need to add a mechanism similar
2404 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2405 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002406 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002407 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002408 if (foregroundWindowHandle &&
2409 foregroundWindowHandle->getInfo()->inputConfig.test(
2410 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002411 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002412 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002413 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2414 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002416 windowHandle->getInfo()->inputConfig.test(
2417 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002418 tempTouchState.addOrUpdateWindow(windowHandle,
2419 InputTarget::Flags::WINDOW_IS_OBSCURED |
2420 InputTarget::Flags::
2421 WINDOW_IS_PARTIALLY_OBSCURED |
2422 InputTarget::Flags::DISPATCH_AS_IS,
2423 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425 }
2426 }
2427 }
2428
2429 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002430 touchedWindows = tempTouchState.windows;
2431 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432
2433 // Drop the outside or hover touch windows since we will not care about them
2434 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002435 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436
2437Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002439 if (switchedDevice) {
2440 if (DEBUG_FOCUS) {
2441 ALOGD("Conflicting pointer actions: Switched to a different device.");
2442 }
2443 *outConflictingPointerActions = true;
2444 }
2445
2446 if (isHoverAction) {
2447 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002448 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002449 ALOGD_IF(DEBUG_FOCUS,
2450 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002451 *outConflictingPointerActions = true;
2452 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002453 tempTouchState.reset();
2454 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2455 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2456 tempTouchState.deviceId = entry.deviceId;
2457 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002458 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002459 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2460 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2461 // All pointers up or canceled.
2462 tempTouchState.reset();
2463 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2464 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002465 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002466 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002467 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002468 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002469 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2470 // One pointer went up.
2471 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2472 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002474 for (size_t i = 0; i < tempTouchState.windows.size();) {
2475 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2476 touchedWindow.pointerIds.clearBit(pointerId);
2477 if (touchedWindow.pointerIds.isEmpty()) {
2478 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2479 continue;
2480 }
2481 i += 1;
2482 }
2483 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2484 // If no split, we suppose all touched windows should receive pointer down.
2485 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2486 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2487 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2488 // Ignore drag window for it should just track one pointer.
2489 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2490 continue;
2491 }
2492 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002496 // Save changes unless the action was scroll in which case the temporary touch
2497 // state was only valid for this one action.
2498 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002499 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002500 mTouchStatesByDisplay[displayId] = tempTouchState;
2501 } else {
2502 mTouchStatesByDisplay.erase(displayId);
2503 }
2504 }
2505
2506 // Update hover state.
2507 mLastHoverWindowHandle = newHoverWindowHandle;
2508
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002509 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510}
2511
arthurhung6d4bed92021-03-17 11:59:33 +08002512void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002513 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2514 // have an explicit reason to support it.
2515 constexpr bool isStylus = false;
2516
chaviw98318de2021-05-19 16:45:23 -05002517 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002518 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002519 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002520 if (dropWindow) {
2521 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002522 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002523 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002524 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002525 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002526 }
2527 mDragState.reset();
2528}
2529
2530void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002531 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002532 return;
2533 }
2534
arthurhung6d4bed92021-03-17 11:59:33 +08002535 if (!mDragState->isStartDrag) {
2536 mDragState->isStartDrag = true;
2537 mDragState->isStylusButtonDownAtStart =
2538 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2539 }
2540
Arthur Hung54745652022-04-20 07:17:41 +00002541 // Find the pointer index by id.
2542 int32_t pointerIndex = 0;
2543 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2544 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2545 if (pointerProperties.id == mDragState->pointerId) {
2546 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002547 }
Arthur Hung54745652022-04-20 07:17:41 +00002548 }
arthurhung6d4bed92021-03-17 11:59:33 +08002549
Arthur Hung54745652022-04-20 07:17:41 +00002550 if (uint32_t(pointerIndex) == entry.pointerCount) {
2551 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002552 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002553 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002554 return;
2555 }
2556
2557 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2558 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2559 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2560
2561 switch (maskedAction) {
2562 case AMOTION_EVENT_ACTION_MOVE: {
2563 // Handle the special case : stylus button no longer pressed.
2564 bool isStylusButtonDown =
2565 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2566 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2567 finishDragAndDrop(entry.displayId, x, y);
2568 return;
2569 }
2570
2571 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2572 // until we have an explicit reason to support it.
2573 constexpr bool isStylus = false;
2574
2575 const sp<WindowInfoHandle> hoverWindowHandle =
2576 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2577 isStylus, false /*addOutsideTargets*/,
2578 true /*ignoreDragWindow*/);
2579 // enqueue drag exit if needed.
2580 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2581 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2582 if (mDragState->dragHoverWindowHandle != nullptr) {
2583 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2584 y);
2585 }
2586 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2587 }
2588 // enqueue drag location if needed.
2589 if (hoverWindowHandle != nullptr) {
2590 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2591 }
2592 break;
2593 }
2594
2595 case AMOTION_EVENT_ACTION_POINTER_UP:
2596 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2597 break;
2598 }
2599 // The drag pointer is up.
2600 [[fallthrough]];
2601 case AMOTION_EVENT_ACTION_UP:
2602 finishDragAndDrop(entry.displayId, x, y);
2603 break;
2604 case AMOTION_EVENT_ACTION_CANCEL: {
2605 ALOGD("Receiving cancel when drag and drop.");
2606 sendDropWindowCommandLocked(nullptr, 0, 0);
2607 mDragState.reset();
2608 break;
2609 }
arthurhungb89ccb02020-12-30 16:19:01 +08002610 }
2611}
2612
chaviw98318de2021-05-19 16:45:23 -05002613void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002614 ftl::Flags<InputTarget::Flags> targetFlags,
2615 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002616 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002617 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002618 std::vector<InputTarget>::iterator it =
2619 std::find_if(inputTargets.begin(), inputTargets.end(),
2620 [&windowHandle](const InputTarget& inputTarget) {
2621 return inputTarget.inputChannel->getConnectionToken() ==
2622 windowHandle->getToken();
2623 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002624
chaviw98318de2021-05-19 16:45:23 -05002625 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002626
2627 if (it == inputTargets.end()) {
2628 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002629 std::shared_ptr<InputChannel> inputChannel =
2630 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002631 if (inputChannel == nullptr) {
2632 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2633 return;
2634 }
2635 inputTarget.inputChannel = inputChannel;
2636 inputTarget.flags = targetFlags;
2637 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002638 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002639 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2640 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002641 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002642 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002643 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002644 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002645 inputTargets.push_back(inputTarget);
2646 it = inputTargets.end() - 1;
2647 }
2648
2649 ALOG_ASSERT(it->flags == targetFlags);
2650 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2651
chaviw1ff3d1e2020-07-01 15:53:47 -07002652 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653}
2654
Michael Wright3dd60e22019-03-27 22:06:44 +00002655void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002656 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002657 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2658 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002659
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002660 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2661 InputTarget target;
2662 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002663 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002664 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2665 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002666 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2667 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002668 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002669 target.setDefaultPointerTransform(target.displayTransform);
2670 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 }
2672}
2673
Robert Carrc9bf1d32020-04-13 17:21:08 -07002674/**
2675 * Indicate whether one window handle should be considered as obscuring
2676 * another window handle. We only check a few preconditions. Actually
2677 * checking the bounds is left to the caller.
2678 */
chaviw98318de2021-05-19 16:45:23 -05002679static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2680 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002681 // Compare by token so cloned layers aren't counted
2682 if (haveSameToken(windowHandle, otherHandle)) {
2683 return false;
2684 }
2685 auto info = windowHandle->getInfo();
2686 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002687 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002688 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002689 } else if (otherInfo->alpha == 0 &&
2690 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002691 // Those act as if they were invisible, so we don't need to flag them.
2692 // We do want to potentially flag touchable windows even if they have 0
2693 // opacity, since they can consume touches and alter the effects of the
2694 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002695 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002696 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2697 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002698 } else if (info->ownerUid == otherInfo->ownerUid) {
2699 // If ownerUid is the same we don't generate occlusion events as there
2700 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002701 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002702 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002703 return false;
2704 } else if (otherInfo->displayId != info->displayId) {
2705 return false;
2706 }
2707 return true;
2708}
2709
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002710/**
2711 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2712 * untrusted, one should check:
2713 *
2714 * 1. If result.hasBlockingOcclusion is true.
2715 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2716 * BLOCK_UNTRUSTED.
2717 *
2718 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2719 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2720 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2721 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2722 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2723 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2724 *
2725 * If neither of those is true, then it means the touch can be allowed.
2726 */
2727InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002728 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2729 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002730 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002731 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002732 TouchOcclusionInfo info;
2733 info.hasBlockingOcclusion = false;
2734 info.obscuringOpacity = 0;
2735 info.obscuringUid = -1;
2736 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002737 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002738 if (windowHandle == otherHandle) {
2739 break; // All future windows are below us. Exit early.
2740 }
chaviw98318de2021-05-19 16:45:23 -05002741 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002742 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2743 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002744 if (DEBUG_TOUCH_OCCLUSION) {
2745 info.debugInfo.push_back(
2746 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2747 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002748 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2749 // we perform the checks below to see if the touch can be propagated or not based on the
2750 // window's touch occlusion mode
2751 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2752 info.hasBlockingOcclusion = true;
2753 info.obscuringUid = otherInfo->ownerUid;
2754 info.obscuringPackage = otherInfo->packageName;
2755 break;
2756 }
2757 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2758 uint32_t uid = otherInfo->ownerUid;
2759 float opacity =
2760 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2761 // Given windows A and B:
2762 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2763 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2764 opacityByUid[uid] = opacity;
2765 if (opacity > info.obscuringOpacity) {
2766 info.obscuringOpacity = opacity;
2767 info.obscuringUid = uid;
2768 info.obscuringPackage = otherInfo->packageName;
2769 }
2770 }
2771 }
2772 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002773 if (DEBUG_TOUCH_OCCLUSION) {
2774 info.debugInfo.push_back(
2775 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2776 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002777 return info;
2778}
2779
chaviw98318de2021-05-19 16:45:23 -05002780std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002781 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002782 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2783 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2784 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2785 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002786 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2787 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2788 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2789 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2790 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002791 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002792 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002793}
2794
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002795bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2796 if (occlusionInfo.hasBlockingOcclusion) {
2797 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2798 occlusionInfo.obscuringUid);
2799 return false;
2800 }
2801 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2802 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2803 "%.2f, maximum allowed = %.2f)",
2804 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2805 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2806 return false;
2807 }
2808 return true;
2809}
2810
chaviw98318de2021-05-19 16:45:23 -05002811bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002814 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2815 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002816 if (windowHandle == otherHandle) {
2817 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
chaviw98318de2021-05-19 16:45:23 -05002819 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002820 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002821 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 return true;
2823 }
2824 }
2825 return false;
2826}
2827
chaviw98318de2021-05-19 16:45:23 -05002828bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002829 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002830 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2831 const WindowInfo* windowInfo = windowHandle->getInfo();
2832 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002833 if (windowHandle == otherHandle) {
2834 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002835 }
chaviw98318de2021-05-19 16:45:23 -05002836 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002837 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002838 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002839 return true;
2840 }
2841 }
2842 return false;
2843}
2844
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002845std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002846 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002847 if (applicationHandle != nullptr) {
2848 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002849 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 } else {
2851 return applicationHandle->getName();
2852 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002853 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002854 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002856 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 }
2858}
2859
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002860void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002861 if (!isUserActivityEvent(eventEntry)) {
2862 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002863 return;
2864 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002865 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002866 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002867 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002868 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002869 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002870 if (DEBUG_DISPATCH_CYCLE) {
2871 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 return;
2874 }
2875 }
2876
2877 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002878 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002879 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002880 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2881 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 return;
2883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002885 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 eventType = USER_ACTIVITY_EVENT_TOUCH;
2887 }
2888 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002890 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002891 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2892 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 return;
2894 }
2895 eventType = USER_ACTIVITY_EVENT_BUTTON;
2896 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002898 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002899 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002900 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002901 break;
2902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 }
2904
Prabir Pradhancef936d2021-07-21 16:17:52 +00002905 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2906 REQUIRES(mLock) {
2907 scoped_unlock unlock(mLock);
2908 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2909 };
2910 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911}
2912
2913void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002915 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002916 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002917 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002919 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002920 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002921 ATRACE_NAME(message.c_str());
2922 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002923 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002924 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002925 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002926 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002927 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2928 inputTarget.getPointerInfoString().c_str());
2929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930
2931 // Skip this event if the connection status is not normal.
2932 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002933 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002934 if (DEBUG_DISPATCH_CYCLE) {
2935 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002936 connection->getInputChannelName().c_str(),
2937 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 return;
2940 }
2941
2942 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002943 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002944 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002945 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002946 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002948 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002949 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002950 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2951 "Splitting motion events requires a down time to be set for the "
2952 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002954 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2955 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 if (!splitMotionEntry) {
2957 return; // split event was dropped
2958 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002959 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2960 std::string reason = std::string("reason=pointer cancel on split window");
2961 android_log_event_list(LOGTAG_INPUT_CANCEL)
2962 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2963 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002964 if (DEBUG_FOCUS) {
2965 ALOGD("channel '%s' ~ Split motion event.",
2966 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002967 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002968 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002969 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2970 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 return;
2972 }
2973 }
2974
2975 // Not splitting. Enqueue dispatch entries for the event as is.
2976 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2977}
2978
2979void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002981 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002982 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002983 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002985 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002986 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002987 ATRACE_NAME(message.c_str());
2988 }
2989
hongzuo liu95785e22022-09-06 02:51:35 +00002990 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991
2992 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002993 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002994 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002995 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002996 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002997 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002998 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002999 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003000 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003001 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003002 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003003 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003004 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005
3006 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003007 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 startDispatchCycleLocked(currentTime, connection);
3009 }
3010}
3011
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003013 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003014 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003015 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003016 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3018 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003019 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003020 ATRACE_NAME(message.c_str());
3021 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003022 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3023 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 return;
3025 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003026
3027 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3028 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029
3030 // This is a new event.
3031 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003032 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003033 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003035 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3036 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003037 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003039 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003040 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003041 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003042 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003043 dispatchEntry->resolvedAction = keyEntry.action;
3044 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3047 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003048 if (DEBUG_DISPATCH_CYCLE) {
3049 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3050 "event",
3051 connection->getInputChannelName().c_str());
3052 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 return; // skip the inconsistent event
3054 }
3055 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003058 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003059 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003060 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3061 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3062 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3063 static_cast<int32_t>(IdGenerator::Source::OTHER);
3064 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003065 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003066 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003067 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003068 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003069 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003071 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003073 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3075 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003076 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003077 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003078 }
3079 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003080 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3081 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003082 if (DEBUG_DISPATCH_CYCLE) {
3083 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3084 "enter event",
3085 connection->getInputChannelName().c_str());
3086 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003087 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3088 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003092 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003093 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3095 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003096 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003097 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3101 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003102 if (DEBUG_DISPATCH_CYCLE) {
3103 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3104 "event",
3105 connection->getInputChannelName().c_str());
3106 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 return; // skip the inconsistent event
3108 }
3109
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003110 dispatchEntry->resolvedEventId =
3111 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3112 ? mIdGenerator.nextId()
3113 : motionEntry.id;
3114 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3115 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3116 ") to MotionEvent(id=0x%" PRIx32 ").",
3117 motionEntry.id, dispatchEntry->resolvedEventId);
3118 ATRACE_NAME(message.c_str());
3119 }
3120
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003121 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3122 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3123 // Skip reporting pointer down outside focus to the policy.
3124 break;
3125 }
3126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003127 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003128 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129
3130 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003132 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003133 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003134 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3135 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003136 break;
3137 }
Chris Yef59a2f42020-10-16 12:55:26 -07003138 case EventEntry::Type::SENSOR: {
3139 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3140 break;
3141 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003142 case EventEntry::Type::CONFIGURATION_CHANGED:
3143 case EventEntry::Type::DEVICE_RESET: {
3144 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003145 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003146 break;
3147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149
3150 // Remember that we are waiting for this dispatch to complete.
3151 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003152 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154
3155 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003156 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003157 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003158}
3159
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003160/**
3161 * This function is purely for debugging. It helps us understand where the user interaction
3162 * was taking place. For example, if user is touching launcher, we will see a log that user
3163 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3164 * We will see both launcher and wallpaper in that list.
3165 * Once the interaction with a particular set of connections starts, no new logs will be printed
3166 * until the set of interacted connections changes.
3167 *
3168 * The following items are skipped, to reduce the logspam:
3169 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3170 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3171 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3172 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3173 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003174 */
3175void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3176 const std::vector<InputTarget>& targets) {
3177 // Skip ACTION_UP events, and all events other than keys and motions
3178 if (entry.type == EventEntry::Type::KEY) {
3179 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3180 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3181 return;
3182 }
3183 } else if (entry.type == EventEntry::Type::MOTION) {
3184 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3185 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3186 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3187 return;
3188 }
3189 } else {
3190 return; // Not a key or a motion
3191 }
3192
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003193 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003194 std::vector<sp<Connection>> newConnections;
3195 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003196 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003197 continue; // Skip windows that receive ACTION_OUTSIDE
3198 }
3199
3200 sp<IBinder> token = target.inputChannel->getConnectionToken();
3201 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003202 if (connection == nullptr) {
3203 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003204 }
3205 newConnectionTokens.insert(std::move(token));
3206 newConnections.emplace_back(connection);
3207 }
3208 if (newConnectionTokens == mInteractionConnectionTokens) {
3209 return; // no change
3210 }
3211 mInteractionConnectionTokens = newConnectionTokens;
3212
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003213 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003214 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003215 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003216 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003217 std::string message = "Interaction with: " + targetList;
3218 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003219 message += "<none>";
3220 }
3221 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3222}
3223
chaviwfd6d3512019-03-25 13:23:49 -07003224void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003225 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003226 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003227 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3228 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003229 return;
3230 }
3231
Vishnu Nairc519ff72021-01-21 08:23:08 -08003232 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003233 if (focusedToken == token) {
3234 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003235 return;
3236 }
3237
Prabir Pradhancef936d2021-07-21 16:17:52 +00003238 auto command = [this, token]() REQUIRES(mLock) {
3239 scoped_unlock unlock(mLock);
3240 mPolicy->onPointerDownOutsideFocus(token);
3241 };
3242 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243}
3244
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003245status_t InputDispatcher::publishMotionEvent(Connection& connection,
3246 DispatchEntry& dispatchEntry) const {
3247 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3248 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3249
3250 PointerCoords scaledCoords[MAX_POINTERS];
3251 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3252
3253 // Set the X and Y offset and X and Y scale depending on the input source.
3254 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003255 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003256 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3257 if (globalScaleFactor != 1.0f) {
3258 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3259 scaledCoords[i] = motionEntry.pointerCoords[i];
3260 // Don't apply window scale here since we don't want scale to affect raw
3261 // coordinates. The scale will be sent back to the client and applied
3262 // later when requesting relative coordinates.
3263 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3264 1 /* windowYScale */);
3265 }
3266 usingCoords = scaledCoords;
3267 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003269 // We don't want the dispatch target to know the coordinates
3270 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3271 scaledCoords[i].clear();
3272 }
3273 usingCoords = scaledCoords;
3274 }
3275
3276 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3277
3278 // Publish the motion event.
3279 return connection.inputPublisher
3280 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3281 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3282 std::move(hmac), dispatchEntry.resolvedAction,
3283 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3284 motionEntry.edgeFlags, motionEntry.metaState,
3285 motionEntry.buttonState, motionEntry.classification,
3286 dispatchEntry.transform, motionEntry.xPrecision,
3287 motionEntry.yPrecision, motionEntry.xCursorPosition,
3288 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3289 motionEntry.downTime, motionEntry.eventTime,
3290 motionEntry.pointerCount, motionEntry.pointerProperties,
3291 usingCoords);
3292}
3293
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003296 if (ATRACE_ENABLED()) {
3297 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003299 ATRACE_NAME(message.c_str());
3300 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003301 if (DEBUG_DISPATCH_CYCLE) {
3302 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003305 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003306 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003308 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003309 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310
3311 // Publish the event.
3312 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3314 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003315 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3317 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003320 status = connection->inputPublisher
3321 .publishKeyEvent(dispatchEntry->seq,
3322 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3323 keyEntry.source, keyEntry.displayId,
3324 std::move(hmac), dispatchEntry->resolvedAction,
3325 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3326 keyEntry.scanCode, keyEntry.metaState,
3327 keyEntry.repeatCount, keyEntry.downTime,
3328 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 }
3331
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003332 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003333 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 break;
3335 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003336
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003337 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003338 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003339 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003340 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003341 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003342 break;
3343 }
3344
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003345 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3346 const TouchModeEntry& touchModeEntry =
3347 static_cast<const TouchModeEntry&>(eventEntry);
3348 status = connection->inputPublisher
3349 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3350 touchModeEntry.inTouchMode);
3351
3352 break;
3353 }
3354
Prabir Pradhan99987712020-11-10 18:43:05 -08003355 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3356 const auto& captureEntry =
3357 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3358 status = connection->inputPublisher
3359 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003360 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003361 break;
3362 }
3363
arthurhungb89ccb02020-12-30 16:19:01 +08003364 case EventEntry::Type::DRAG: {
3365 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3366 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3367 dragEntry.id, dragEntry.x,
3368 dragEntry.y,
3369 dragEntry.isExiting);
3370 break;
3371 }
3372
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003373 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003374 case EventEntry::Type::DEVICE_RESET:
3375 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003376 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003377 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 }
3381
3382 // Check the result.
3383 if (status) {
3384 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003385 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 "This is unexpected because the wait queue is empty, so the pipe "
3388 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003389 "event to it, status=%s(%d)",
3390 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3391 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3393 } else {
3394 // Pipe is full and we are waiting for the app to finish process some events
3395 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003396 if (DEBUG_DISPATCH_CYCLE) {
3397 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3398 "waiting for the application to catch up",
3399 connection->getInputChannelName().c_str());
3400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 }
3402 } else {
3403 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003404 "status=%s(%d)",
3405 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3406 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3408 }
3409 return;
3410 }
3411
3412 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003413 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3414 connection->outboundQueue.end(),
3415 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003416 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003417 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003418 if (connection->responsive) {
3419 mAnrTracker.insert(dispatchEntry->timeoutTime,
3420 connection->inputChannel->getConnectionToken());
3421 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003422 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424}
3425
chaviw09c8d2d2020-08-24 15:48:26 -07003426std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3427 size_t size;
3428 switch (event.type) {
3429 case VerifiedInputEvent::Type::KEY: {
3430 size = sizeof(VerifiedKeyEvent);
3431 break;
3432 }
3433 case VerifiedInputEvent::Type::MOTION: {
3434 size = sizeof(VerifiedMotionEvent);
3435 break;
3436 }
3437 }
3438 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3439 return mHmacKeyManager.sign(start, size);
3440}
3441
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003442const std::array<uint8_t, 32> InputDispatcher::getSignature(
3443 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003444 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3445 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003446 // Only sign events up and down events as the purely move events
3447 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003448 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003449 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003450
3451 VerifiedMotionEvent verifiedEvent =
3452 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3453 verifiedEvent.actionMasked = actionMasked;
3454 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3455 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003456}
3457
3458const std::array<uint8_t, 32> InputDispatcher::getSignature(
3459 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3460 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3461 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3462 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003463 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003464}
3465
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003467 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003468 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003469 if (DEBUG_DISPATCH_CYCLE) {
3470 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3471 connection->getInputChannelName().c_str(), seq, toString(handled));
3472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003474 if (connection->status == Connection::Status::BROKEN ||
3475 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 return;
3477 }
3478
3479 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003480 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3481 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3482 };
3483 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484}
3485
3486void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003487 const sp<Connection>& connection,
3488 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003489 if (DEBUG_DISPATCH_CYCLE) {
3490 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3491 connection->getInputChannelName().c_str(), toString(notify));
3492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493
3494 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003495 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003496 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003497 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003498 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
3500 // The connection appears to be unrecoverably broken.
3501 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003502 if (connection->status == Connection::Status::NORMAL) {
3503 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504
3505 if (notify) {
3506 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003507 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3508 connection->getInputChannelName().c_str());
3509
3510 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003511 scoped_unlock unlock(mLock);
3512 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3513 };
3514 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 }
3516 }
3517}
3518
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003519void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3520 while (!queue.empty()) {
3521 DispatchEntry* dispatchEntry = queue.front();
3522 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003523 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 }
3525}
3526
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003527void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003529 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 }
3531 delete dispatchEntry;
3532}
3533
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003534int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3535 std::scoped_lock _l(mLock);
3536 sp<Connection> connection = getConnectionLocked(connectionToken);
3537 if (connection == nullptr) {
3538 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3539 connectionToken.get(), events);
3540 return 0; // remove the callback
3541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003543 bool notify;
3544 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3545 if (!(events & ALOOPER_EVENT_INPUT)) {
3546 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3547 "events=0x%x",
3548 connection->getInputChannelName().c_str(), events);
3549 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 }
3551
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003552 nsecs_t currentTime = now();
3553 bool gotOne = false;
3554 status_t status = OK;
3555 for (;;) {
3556 Result<InputPublisher::ConsumerResponse> result =
3557 connection->inputPublisher.receiveConsumerResponse();
3558 if (!result.ok()) {
3559 status = result.error().code();
3560 break;
3561 }
3562
3563 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3564 const InputPublisher::Finished& finish =
3565 std::get<InputPublisher::Finished>(*result);
3566 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3567 finish.consumeTime);
3568 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003569 if (shouldReportMetricsForConnection(*connection)) {
3570 const InputPublisher::Timeline& timeline =
3571 std::get<InputPublisher::Timeline>(*result);
3572 mLatencyTracker
3573 .trackGraphicsLatency(timeline.inputEventId,
3574 connection->inputChannel->getConnectionToken(),
3575 std::move(timeline.graphicsTimeline));
3576 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003577 }
3578 gotOne = true;
3579 }
3580 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003581 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003582 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 return 1;
3584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 }
3586
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003587 notify = status != DEAD_OBJECT || !connection->monitor;
3588 if (notify) {
3589 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3590 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3591 status);
3592 }
3593 } else {
3594 // Monitor channels are never explicitly unregistered.
3595 // We do it automatically when the remote endpoint is closed so don't warn about them.
3596 const bool stillHaveWindowHandle =
3597 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3598 notify = !connection->monitor && stillHaveWindowHandle;
3599 if (notify) {
3600 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3601 connection->getInputChannelName().c_str(), events);
3602 }
3603 }
3604
3605 // Remove the channel.
3606 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3607 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608}
3609
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003610void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003612 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003613 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 }
3615}
3616
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003617void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003618 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003619 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003620 for (const Monitor& monitor : monitors) {
3621 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003622 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003623 }
3624}
3625
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003627 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003628 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003629 if (connection == nullptr) {
3630 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003632
3633 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634}
3635
3636void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3637 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003638 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 return;
3640 }
3641
3642 nsecs_t currentTime = now();
3643
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003644 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003645 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003647 if (cancelationEvents.empty()) {
3648 return;
3649 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003650 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3651 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3652 "with reality: %s, mode=%d.",
3653 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3654 options.mode);
3655 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003656
Arthur Hungb3307ee2021-10-14 10:57:37 +00003657 std::string reason = std::string("reason=").append(options.reason);
3658 android_log_event_list(LOGTAG_INPUT_CANCEL)
3659 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3660
Svet Ganov5d3bc372020-01-26 23:11:07 -08003661 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003662 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003663 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3664 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003665 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003666 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003667 target.globalScaleFactor = windowInfo->globalScaleFactor;
3668 }
3669 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003670 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003671
hongzuo liu95785e22022-09-06 02:51:35 +00003672 const bool wasEmpty = connection->outboundQueue.empty();
3673
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003674 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003676 switch (cancelationEventEntry->type) {
3677 case EventEntry::Type::KEY: {
3678 logOutboundKeyDetails("cancel - ",
3679 static_cast<const KeyEntry&>(*cancelationEventEntry));
3680 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003682 case EventEntry::Type::MOTION: {
3683 logOutboundMotionDetails("cancel - ",
3684 static_cast<const MotionEntry&>(*cancelationEventEntry));
3685 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003687 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003688 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003689 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3690 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003691 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003692 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003693 break;
3694 }
3695 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003696 case EventEntry::Type::DEVICE_RESET:
3697 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003698 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003699 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003700 break;
3701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 }
3703
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003705 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003707
hongzuo liu95785e22022-09-06 02:51:35 +00003708 // If the outbound queue was previously empty, start the dispatch cycle going.
3709 if (wasEmpty && !connection->outboundQueue.empty()) {
3710 startDispatchCycleLocked(currentTime, connection);
3711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712}
3713
Svet Ganov5d3bc372020-01-26 23:11:07 -08003714void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003715 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003716 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003717 return;
3718 }
3719
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003720 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003721 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003722
3723 if (downEvents.empty()) {
3724 return;
3725 }
3726
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003727 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003728 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3729 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003730 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731
3732 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003733 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003734 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3735 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003736 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003737 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003738 target.globalScaleFactor = windowInfo->globalScaleFactor;
3739 }
3740 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003741 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003742
hongzuo liu95785e22022-09-06 02:51:35 +00003743 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003744 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003745 switch (downEventEntry->type) {
3746 case EventEntry::Type::MOTION: {
3747 logOutboundMotionDetails("down - ",
3748 static_cast<const MotionEntry&>(*downEventEntry));
3749 break;
3750 }
3751
3752 case EventEntry::Type::KEY:
3753 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003754 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003755 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003756 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003757 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003758 case EventEntry::Type::SENSOR:
3759 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003760 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003761 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003762 break;
3763 }
3764 }
3765
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003766 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003767 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003768 }
3769
hongzuo liu95785e22022-09-06 02:51:35 +00003770 // If the outbound queue was previously empty, start the dispatch cycle going.
3771 if (wasEmpty && !connection->outboundQueue.empty()) {
3772 startDispatchCycleLocked(downTime, connection);
3773 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003774}
3775
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003776std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003777 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 ALOG_ASSERT(pointerIds.value != 0);
3779
3780 uint32_t splitPointerIndexMap[MAX_POINTERS];
3781 PointerProperties splitPointerProperties[MAX_POINTERS];
3782 PointerCoords splitPointerCoords[MAX_POINTERS];
3783
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003784 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 uint32_t splitPointerCount = 0;
3786
3787 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003790 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 uint32_t pointerId = uint32_t(pointerProperties.id);
3792 if (pointerIds.hasBit(pointerId)) {
3793 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3794 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3795 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003796 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 splitPointerCount += 1;
3798 }
3799 }
3800
3801 if (splitPointerCount != pointerIds.count()) {
3802 // This is bad. We are missing some of the pointers that we expected to deliver.
3803 // Most likely this indicates that we received an ACTION_MOVE events that has
3804 // different pointer ids than we expected based on the previous ACTION_DOWN
3805 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3806 // in this way.
3807 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003808 "we expected there to be %d pointers. This probably means we received "
3809 "a broken sequence of pointer ids from the input device.",
3810 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003811 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003814 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003816 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3817 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3819 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003820 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 uint32_t pointerId = uint32_t(pointerProperties.id);
3822 if (pointerIds.hasBit(pointerId)) {
3823 if (pointerIds.count() == 1) {
3824 // The first/last pointer went down/up.
3825 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003827 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3828 ? AMOTION_EVENT_ACTION_CANCEL
3829 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 } else {
3831 // A secondary pointer went down/up.
3832 uint32_t splitPointerIndex = 0;
3833 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3834 splitPointerIndex += 1;
3835 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003836 action = maskedAction |
3837 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839 } else {
3840 // An unrelated pointer changed.
3841 action = AMOTION_EVENT_ACTION_MOVE;
3842 }
3843 }
3844
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003845 if (action == AMOTION_EVENT_ACTION_DOWN) {
3846 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3847 "Split motion event has mismatching downTime and eventTime for "
3848 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3849 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3850 }
3851
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003852 int32_t newId = mIdGenerator.nextId();
3853 if (ATRACE_ENABLED()) {
3854 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3855 ") to MotionEvent(id=0x%" PRIx32 ").",
3856 originalMotionEntry.id, newId);
3857 ATRACE_NAME(message.c_str());
3858 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003859 std::unique_ptr<MotionEntry> splitMotionEntry =
3860 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3861 originalMotionEntry.deviceId, originalMotionEntry.source,
3862 originalMotionEntry.displayId,
3863 originalMotionEntry.policyFlags, action,
3864 originalMotionEntry.actionButton,
3865 originalMotionEntry.flags, originalMotionEntry.metaState,
3866 originalMotionEntry.buttonState,
3867 originalMotionEntry.classification,
3868 originalMotionEntry.edgeFlags,
3869 originalMotionEntry.xPrecision,
3870 originalMotionEntry.yPrecision,
3871 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003872 originalMotionEntry.yCursorPosition, splitDownTime,
3873 splitPointerCount, splitPointerProperties,
3874 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003876 if (originalMotionEntry.injectionState) {
3877 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 splitMotionEntry->injectionState->refCount += 1;
3879 }
3880
3881 return splitMotionEntry;
3882}
3883
3884void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003885 if (DEBUG_INBOUND_EVENT_DETAILS) {
3886 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888
Antonio Kantekf16f2832021-09-28 04:39:20 +00003889 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003891 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003893 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3894 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3895 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 } // release lock
3897
3898 if (needWake) {
3899 mLooper->wake();
3900 }
3901}
3902
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003903/**
3904 * If one of the meta shortcuts is detected, process them here:
3905 * Meta + Backspace -> generate BACK
3906 * Meta + Enter -> generate HOME
3907 * This will potentially overwrite keyCode and metaState.
3908 */
3909void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003910 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003911 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3912 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3913 if (keyCode == AKEYCODE_DEL) {
3914 newKeyCode = AKEYCODE_BACK;
3915 } else if (keyCode == AKEYCODE_ENTER) {
3916 newKeyCode = AKEYCODE_HOME;
3917 }
3918 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003919 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003921 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003922 keyCode = newKeyCode;
3923 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3924 }
3925 } else if (action == AKEY_EVENT_ACTION_UP) {
3926 // In order to maintain a consistent stream of up and down events, check to see if the key
3927 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3928 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003929 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003930 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003931 auto replacementIt = mReplacedKeys.find(replacement);
3932 if (replacementIt != mReplacedKeys.end()) {
3933 keyCode = replacementIt->second;
3934 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003935 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3936 }
3937 }
3938}
3939
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 if (DEBUG_INBOUND_EVENT_DETAILS) {
3942 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3943 "policyFlags=0x%x, action=0x%x, "
3944 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3945 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3946 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3947 args->downTime);
3948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 if (!validateKeyEvent(args->action)) {
3950 return;
3951 }
3952
3953 uint32_t policyFlags = args->policyFlags;
3954 int32_t flags = args->flags;
3955 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003956 // InputDispatcher tracks and generates key repeats on behalf of
3957 // whatever notifies it, so repeatCount should always be set to 0
3958 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3960 policyFlags |= POLICY_FLAG_VIRTUAL;
3961 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 if (policyFlags & POLICY_FLAG_FUNCTION) {
3964 metaState |= AMETA_FUNCTION_ON;
3965 }
3966
3967 policyFlags |= POLICY_FLAG_TRUSTED;
3968
Michael Wright78f24442014-08-06 15:55:28 -07003969 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003970 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003971
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003973 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003974 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3975 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
Michael Wright2b3c3302018-03-02 17:19:13 +00003977 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003979 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3980 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983
Antonio Kantekf16f2832021-09-28 04:39:20 +00003984 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 { // acquire lock
3986 mLock.lock();
3987
3988 if (shouldSendKeyToInputFilterLocked(args)) {
3989 mLock.unlock();
3990
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003991 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3993 return; // event was consumed by the filter
3994 }
3995
3996 mLock.lock();
3997 }
3998
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003999 std::unique_ptr<KeyEntry> newEntry =
4000 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4001 args->displayId, policyFlags, args->action, flags,
4002 keyCode, args->scanCode, metaState, repeatCount,
4003 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004005 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 mLock.unlock();
4007 } // release lock
4008
4009 if (needWake) {
4010 mLooper->wake();
4011 }
4012}
4013
4014bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4015 return mInputFilterEnabled;
4016}
4017
4018void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004019 if (DEBUG_INBOUND_EVENT_DETAILS) {
4020 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4021 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004022 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004023 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4024 "yCursorPosition=%f, downTime=%" PRId64,
4025 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004026 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4027 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4028 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4029 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004030 for (uint32_t i = 0; i < args->pointerCount; i++) {
4031 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4032 "x=%f, y=%f, pressure=%f, size=%f, "
4033 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4034 "orientation=%f",
4035 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4036 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4037 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4038 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4039 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4040 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4041 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4042 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4043 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4044 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4048 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 return;
4050 }
4051
4052 uint32_t policyFlags = args->policyFlags;
4053 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004054
4055 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004056 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004057 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4058 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061
Antonio Kantekf16f2832021-09-28 04:39:20 +00004062 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 { // acquire lock
4064 mLock.lock();
4065
4066 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004067 ui::Transform displayTransform;
4068 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4069 displayTransform = it->second.transform;
4070 }
4071
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 mLock.unlock();
4073
4074 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004075 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4076 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004077 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004078 displayTransform, args->xPrecision, args->yPrecision,
4079 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004080 args->downTime, args->eventTime, args->pointerCount,
4081 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082
4083 policyFlags |= POLICY_FLAG_FILTERED;
4084 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4085 return; // event was consumed by the filter
4086 }
4087
4088 mLock.lock();
4089 }
4090
4091 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004092 std::unique_ptr<MotionEntry> newEntry =
4093 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4094 args->source, args->displayId, policyFlags,
4095 args->action, args->actionButton, args->flags,
4096 args->metaState, args->buttonState,
4097 args->classification, args->edgeFlags,
4098 args->xPrecision, args->yPrecision,
4099 args->xCursorPosition, args->yCursorPosition,
4100 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004101 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004103 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4104 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4105 !mInputFilterEnabled) {
4106 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4107 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4108 }
4109
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004110 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 mLock.unlock();
4112 } // release lock
4113
4114 if (needWake) {
4115 mLooper->wake();
4116 }
4117}
4118
Chris Yef59a2f42020-10-16 12:55:26 -07004119void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004120 if (DEBUG_INBOUND_EVENT_DETAILS) {
4121 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4122 " sensorType=%s",
4123 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004124 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004125 }
Chris Yef59a2f42020-10-16 12:55:26 -07004126
Antonio Kantekf16f2832021-09-28 04:39:20 +00004127 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004128 { // acquire lock
4129 mLock.lock();
4130
4131 // Just enqueue a new sensor event.
4132 std::unique_ptr<SensorEntry> newEntry =
4133 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4134 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4135 args->sensorType, args->accuracy,
4136 args->accuracyChanged, args->values);
4137
4138 needWake = enqueueInboundEventLocked(std::move(newEntry));
4139 mLock.unlock();
4140 } // release lock
4141
4142 if (needWake) {
4143 mLooper->wake();
4144 }
4145}
4146
Chris Yefb552902021-02-03 17:18:37 -08004147void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004148 if (DEBUG_INBOUND_EVENT_DETAILS) {
4149 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4150 args->deviceId, args->isOn);
4151 }
Chris Yefb552902021-02-03 17:18:37 -08004152 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4153}
4154
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004156 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157}
4158
4159void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004160 if (DEBUG_INBOUND_EVENT_DETAILS) {
4161 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4162 "switchMask=0x%08x",
4163 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165
4166 uint32_t policyFlags = args->policyFlags;
4167 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169}
4170
4171void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004172 if (DEBUG_INBOUND_EVENT_DETAILS) {
4173 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4174 args->deviceId);
4175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176
Antonio Kantekf16f2832021-09-28 04:39:20 +00004177 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004179 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 std::unique_ptr<DeviceResetEntry> newEntry =
4182 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4183 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 } // release lock
4185
4186 if (needWake) {
4187 mLooper->wake();
4188 }
4189}
4190
Prabir Pradhan7e186182020-11-10 13:56:45 -08004191void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004192 if (DEBUG_INBOUND_EVENT_DETAILS) {
4193 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004194 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004195 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004196
Antonio Kantekf16f2832021-09-28 04:39:20 +00004197 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004198 { // acquire lock
4199 std::scoped_lock _l(mLock);
4200 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004201 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004202 needWake = enqueueInboundEventLocked(std::move(entry));
4203 } // release lock
4204
4205 if (needWake) {
4206 mLooper->wake();
4207 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004208}
4209
Prabir Pradhan5735a322022-04-11 17:23:34 +00004210InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4211 std::optional<int32_t> targetUid,
4212 InputEventInjectionSync syncMode,
4213 std::chrono::milliseconds timeout,
4214 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004215 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004216 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4217 "policyFlags=0x%08x",
4218 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4219 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004220 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004221 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222
Prabir Pradhan5735a322022-04-11 17:23:34 +00004223 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004225 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004226 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4227 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4228 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4229 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4230 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004231 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004232 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004233 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 }
4235
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004239 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4240 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004242 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004245 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004246 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4247 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4248 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004249 int32_t keyCode = incomingKey.getKeyCode();
4250 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004251 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004253 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004254 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004255 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4256 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4257 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4260 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004261 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262
4263 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4264 android::base::Timer t;
4265 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4266 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4267 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4268 std::to_string(t.duration().count()).c_str());
4269 }
4270 }
4271
4272 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004273 std::unique_ptr<KeyEntry> injectedEntry =
4274 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004275 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276 incomingKey.getDisplayId(), policyFlags, action,
4277 flags, keyCode, incomingKey.getScanCode(), metaState,
4278 incomingKey.getRepeatCount(),
4279 incomingKey.getDownTime());
4280 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004285 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004286 const int32_t action = motionEvent.getAction();
4287 const bool isPointerEvent =
4288 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4289 // If a pointer event has no displayId specified, inject it to the default display.
4290 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4291 ? ADISPLAY_ID_DEFAULT
4292 : event->getDisplayId();
4293 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004294 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004295 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004296 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004298 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 }
4300
4301 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004302 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004303 android::base::Timer t;
4304 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4305 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4306 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4307 std::to_string(t.duration().count()).c_str());
4308 }
4309 }
4310
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004311 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4312 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4313 }
4314
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004316 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4317 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004318 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004319 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4320 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004321 displayId, policyFlags, action, actionButton,
4322 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004323 motionEvent.getButtonState(),
4324 motionEvent.getClassification(),
4325 motionEvent.getEdgeFlags(),
4326 motionEvent.getXPrecision(),
4327 motionEvent.getYPrecision(),
4328 motionEvent.getRawXCursorPosition(),
4329 motionEvent.getRawYCursorPosition(),
4330 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004331 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004332 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004333 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004334 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004335 sampleEventTimes += 1;
4336 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004337 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004338 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4339 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004340 displayId, policyFlags, action, actionButton,
4341 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004342 motionEvent.getButtonState(),
4343 motionEvent.getClassification(),
4344 motionEvent.getEdgeFlags(),
4345 motionEvent.getXPrecision(),
4346 motionEvent.getYPrecision(),
4347 motionEvent.getRawXCursorPosition(),
4348 motionEvent.getRawYCursorPosition(),
4349 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004350 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004351 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004352 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4353 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004354 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004355 }
4356 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004360 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004361 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 }
4363
Prabir Pradhan5735a322022-04-11 17:23:34 +00004364 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 injectionState->injectionIsAsync = true;
4367 }
4368
4369 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004370 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
4372 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004373 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004374 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004375 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 }
4377
4378 mLock.unlock();
4379
4380 if (needWake) {
4381 mLooper->wake();
4382 }
4383
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004386 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 if (syncMode == InputEventInjectionSync::NONE) {
4389 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 } else {
4391 for (;;) {
4392 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 break;
4395 }
4396
4397 nsecs_t remainingTimeout = endTime - now();
4398 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004399 if (DEBUG_INJECTION) {
4400 ALOGD("injectInputEvent - Timed out waiting for injection result "
4401 "to become available.");
4402 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 break;
4405 }
4406
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004407 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 }
4409
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004410 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4411 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004413 if (DEBUG_INJECTION) {
4414 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4415 injectionState->pendingForegroundDispatches);
4416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 nsecs_t remainingTimeout = endTime - now();
4418 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004419 if (DEBUG_INJECTION) {
4420 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4421 "dispatches to finish.");
4422 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004423 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 break;
4425 }
4426
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004427 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 }
4429 }
4430 }
4431
4432 injectionState->release();
4433 } // release lock
4434
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004435 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004436 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438
4439 return injectionResult;
4440}
4441
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004442std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004443 std::array<uint8_t, 32> calculatedHmac;
4444 std::unique_ptr<VerifiedInputEvent> result;
4445 switch (event.getType()) {
4446 case AINPUT_EVENT_TYPE_KEY: {
4447 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4448 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4449 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004450 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004451 break;
4452 }
4453 case AINPUT_EVENT_TYPE_MOTION: {
4454 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4455 VerifiedMotionEvent verifiedMotionEvent =
4456 verifiedMotionEventFromMotionEvent(motionEvent);
4457 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004458 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004459 break;
4460 }
4461 default: {
4462 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4463 return nullptr;
4464 }
4465 }
4466 if (calculatedHmac == INVALID_HMAC) {
4467 return nullptr;
4468 }
4469 if (calculatedHmac != event.getHmac()) {
4470 return nullptr;
4471 }
4472 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004473}
4474
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004475void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004476 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004477 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004479 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004480 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004483 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 // Log the outcome since the injector did not wait for the injection result.
4485 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004486 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004487 ALOGV("Asynchronous input event injection succeeded.");
4488 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004489 case InputEventInjectionResult::TARGET_MISMATCH:
4490 ALOGV("Asynchronous input event injection target mismatch.");
4491 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004492 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004493 ALOGW("Asynchronous input event injection failed.");
4494 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 ALOGW("Asynchronous input event injection timed out.");
4497 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004498 case InputEventInjectionResult::PENDING:
4499 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4500 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 }
4502 }
4503
4504 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004505 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 }
4507}
4508
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004509void InputDispatcher::transformMotionEntryForInjectionLocked(
4510 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004511 // Input injection works in the logical display coordinate space, but the input pipeline works
4512 // display space, so we need to transform the injected events accordingly.
4513 const auto it = mDisplayInfos.find(entry.displayId);
4514 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004515 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004516
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004517 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4518 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4519 const vec2 cursor =
4520 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4521 {entry.xCursorPosition, entry.yCursorPosition});
4522 entry.xCursorPosition = cursor.x;
4523 entry.yCursorPosition = cursor.y;
4524 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004525 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004526 entry.pointerCoords[i] =
4527 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4528 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004529 }
4530}
4531
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004532void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4533 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 if (injectionState) {
4535 injectionState->pendingForegroundDispatches += 1;
4536 }
4537}
4538
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004539void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4540 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 if (injectionState) {
4542 injectionState->pendingForegroundDispatches -= 1;
4543
4544 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004545 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 }
4547 }
4548}
4549
chaviw98318de2021-05-19 16:45:23 -05004550const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004551 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004552 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004553 auto it = mWindowHandlesByDisplay.find(displayId);
4554 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004555}
4556
chaviw98318de2021-05-19 16:45:23 -05004557sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004558 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004559 if (windowHandleToken == nullptr) {
4560 return nullptr;
4561 }
4562
Arthur Hungb92218b2018-08-14 12:00:21 +08004563 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004564 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4565 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004566 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004567 return windowHandle;
4568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 }
4570 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004571 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572}
4573
chaviw98318de2021-05-19 16:45:23 -05004574sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4575 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004576 if (windowHandleToken == nullptr) {
4577 return nullptr;
4578 }
4579
chaviw98318de2021-05-19 16:45:23 -05004580 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004581 if (windowHandle->getToken() == windowHandleToken) {
4582 return windowHandle;
4583 }
4584 }
4585 return nullptr;
4586}
4587
chaviw98318de2021-05-19 16:45:23 -05004588sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4589 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004590 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004591 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4592 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004593 if (handle->getId() == windowHandle->getId() &&
4594 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004595 if (windowHandle->getInfo()->displayId != it.first) {
4596 ALOGE("Found window %s in display %" PRId32
4597 ", but it should belong to display %" PRId32,
4598 windowHandle->getName().c_str(), it.first,
4599 windowHandle->getInfo()->displayId);
4600 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004601 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004605 return nullptr;
4606}
4607
chaviw98318de2021-05-19 16:45:23 -05004608sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004609 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4610 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611}
4612
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004613bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4614 const MotionEntry& motionEntry) const {
4615 const WindowInfo& info = *window->getInfo();
4616
4617 // Skip spy window targets that are not valid for targeted injection.
4618 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004619 return false;
4620 }
4621
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004622 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4623 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4624 return false;
4625 }
4626
4627 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4628 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4629 window->getName().c_str());
4630 return false;
4631 }
4632
4633 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004634 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004635 ALOGW("Not sending touch to %s because there's no corresponding connection",
4636 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004637 return false;
4638 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004639
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004640 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004641 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004642 return false;
4643 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004644
4645 // Drop events that can't be trusted due to occlusion
4646 const auto [x, y] = resolveTouchedPosition(motionEntry);
4647 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4648 if (!isTouchTrustedLocked(occlusionInfo)) {
4649 if (DEBUG_TOUCH_OCCLUSION) {
4650 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4651 for (const auto& log : occlusionInfo.debugInfo) {
4652 ALOGD("%s", log.c_str());
4653 }
4654 }
4655 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4656 occlusionInfo.obscuringUid);
4657 return false;
4658 }
4659
4660 // Drop touch events if requested by input feature
4661 if (shouldDropInput(motionEntry, window)) {
4662 return false;
4663 }
4664
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004665 return true;
4666}
4667
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004668std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4669 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004670 auto connectionIt = mConnectionsByToken.find(token);
4671 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004672 return nullptr;
4673 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004674 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004675}
4676
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004677void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004678 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4679 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004680 // Remove all handles on a display if there are no windows left.
4681 mWindowHandlesByDisplay.erase(displayId);
4682 return;
4683 }
4684
4685 // Since we compare the pointer of input window handles across window updates, we need
4686 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004687 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4688 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4689 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004690 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004691 }
4692
chaviw98318de2021-05-19 16:45:23 -05004693 std::vector<sp<WindowInfoHandle>> newHandles;
4694 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004695 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004696 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004697 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004698 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004699 const bool canReceiveInput =
4700 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4701 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004702 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004703 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004704 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004705 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004706 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004707 }
4708
4709 if (info->displayId != displayId) {
4710 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4711 handle->getName().c_str(), displayId, info->displayId);
4712 continue;
4713 }
4714
Robert Carredd13602020-04-13 17:24:34 -07004715 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4716 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004717 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004718 oldHandle->updateFrom(handle);
4719 newHandles.push_back(oldHandle);
4720 } else {
4721 newHandles.push_back(handle);
4722 }
4723 }
4724
4725 // Insert or replace
4726 mWindowHandlesByDisplay[displayId] = newHandles;
4727}
4728
Arthur Hung72d8dc32020-03-28 00:48:39 +00004729void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004730 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004731 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004732 { // acquire lock
4733 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004734 for (const auto& [displayId, handles] : handlesPerDisplay) {
4735 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004736 }
4737 }
4738 // Wake up poll loop since it may need to make new input dispatching choices.
4739 mLooper->wake();
4740}
4741
Arthur Hungb92218b2018-08-14 12:00:21 +08004742/**
4743 * Called from InputManagerService, update window handle list by displayId that can receive input.
4744 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4745 * If set an empty list, remove all handles from the specific display.
4746 * For focused handle, check if need to change and send a cancel event to previous one.
4747 * For removed handle, check if need to send a cancel event if already in touch.
4748 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004749void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004750 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004751 if (DEBUG_FOCUS) {
4752 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004753 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004754 windowList += iwh->getName() + " ";
4755 }
4756 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
Prabir Pradhand65552b2021-10-07 11:23:50 -07004759 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004760 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004761 const WindowInfo& info = *window->getInfo();
4762
4763 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004764 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004765 if (noInputWindow && window->getToken() != nullptr) {
4766 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4767 window->getName().c_str());
4768 window->releaseChannel();
4769 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004770
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004771 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004772 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4773 !info.inputConfig.test(
4774 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004775 "%s has feature SPY, but is not a trusted overlay.",
4776 window->getName().c_str());
4777
Prabir Pradhand65552b2021-10-07 11:23:50 -07004778 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004779 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4780 !info.inputConfig.test(
4781 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004782 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4783 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004784 }
4785
Arthur Hung72d8dc32020-03-28 00:48:39 +00004786 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004787 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004789 // Save the old windows' orientation by ID before it gets updated.
4790 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004791 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004792 oldWindowOrientations.emplace(handle->getId(),
4793 handle->getInfo()->transform.getOrientation());
4794 }
4795
chaviw98318de2021-05-19 16:45:23 -05004796 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004797
chaviw98318de2021-05-19 16:45:23 -05004798 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004799 if (mLastHoverWindowHandle &&
4800 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4801 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004802 mLastHoverWindowHandle = nullptr;
4803 }
4804
Vishnu Nairc519ff72021-01-21 08:23:08 -08004805 std::optional<FocusResolver::FocusChanges> changes =
4806 mFocusResolver.setInputWindows(displayId, windowHandles);
4807 if (changes) {
4808 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004811 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4812 mTouchStatesByDisplay.find(displayId);
4813 if (stateIt != mTouchStatesByDisplay.end()) {
4814 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004815 for (size_t i = 0; i < state.windows.size();) {
4816 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004817 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004818 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004819 ALOGD("Touched window was removed: %s in display %" PRId32,
4820 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004821 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004822 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004823 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4824 if (touchedInputChannel != nullptr) {
4825 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4826 "touched window was removed");
4827 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004828 // Since we are about to drop the touch, cancel the events for the wallpaper as
4829 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004830 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004831 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4832 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004833 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4834 if (wallpaper != nullptr) {
4835 sp<Connection> wallpaperConnection =
4836 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004837 if (wallpaperConnection != nullptr) {
4838 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4839 options);
4840 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004841 }
4842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004844 state.windows.erase(state.windows.begin() + i);
4845 } else {
4846 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
4848 }
arthurhungb89ccb02020-12-30 16:19:01 +08004849
arthurhung6d4bed92021-03-17 11:59:33 +08004850 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004851 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004852 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004853 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004854 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004855 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4856 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004857 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004858 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004859 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004860
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004861 // Determine if the orientation of any of the input windows have changed, and cancel all
4862 // pointer events if necessary.
4863 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4864 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4865 if (newWindowHandle != nullptr &&
4866 newWindowHandle->getInfo()->transform.getOrientation() !=
4867 oldWindowOrientations[oldWindowHandle->getId()]) {
4868 std::shared_ptr<InputChannel> inputChannel =
4869 getInputChannelLocked(newWindowHandle->getToken());
4870 if (inputChannel != nullptr) {
4871 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4872 "touched window's orientation changed");
4873 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004874 }
4875 }
4876 }
4877
Arthur Hung72d8dc32020-03-28 00:48:39 +00004878 // Release information for windows that are no longer present.
4879 // This ensures that unused input channels are released promptly.
4880 // Otherwise, they might stick around until the window handle is destroyed
4881 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004882 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004883 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004884 if (DEBUG_FOCUS) {
4885 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004886 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004887 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004888 }
chaviw291d88a2019-02-14 10:33:58 -08004889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890}
4891
4892void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004893 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004894 if (DEBUG_FOCUS) {
4895 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4896 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4897 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004899 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004900 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 } // release lock
4902
4903 // Wake up poll loop since it may need to make new input dispatching choices.
4904 mLooper->wake();
4905}
4906
Vishnu Nair599f1412021-06-21 10:39:58 -07004907void InputDispatcher::setFocusedApplicationLocked(
4908 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4909 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4910 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4911
4912 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4913 return; // This application is already focused. No need to wake up or change anything.
4914 }
4915
4916 // Set the new application handle.
4917 if (inputApplicationHandle != nullptr) {
4918 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4919 } else {
4920 mFocusedApplicationHandlesByDisplay.erase(displayId);
4921 }
4922
4923 // No matter what the old focused application was, stop waiting on it because it is
4924 // no longer focused.
4925 resetNoFocusedWindowTimeoutLocked();
4926}
4927
Tiger Huang721e26f2018-07-24 22:26:19 +08004928/**
4929 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4930 * the display not specified.
4931 *
4932 * We track any unreleased events for each window. If a window loses the ability to receive the
4933 * released event, we will send a cancel event to it. So when the focused display is changed, we
4934 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4935 * display. The display-specified events won't be affected.
4936 */
4937void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004938 if (DEBUG_FOCUS) {
4939 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4940 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004941 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004942 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004943
4944 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004945 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004946 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004947 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004948 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004949 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004950 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 CancelationOptions
4952 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4953 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004954 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004955 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4956 }
4957 }
4958 mFocusedDisplayId = displayId;
4959
Chris Ye3c2d6f52020-08-09 10:39:48 -07004960 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004961 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004962 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004963
Vishnu Nairad321cd2020-08-20 16:40:21 -07004964 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004965 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004966 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004967 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004968 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004969 }
4970 }
4971 }
4972
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004973 if (DEBUG_FOCUS) {
4974 logDispatchStateLocked();
4975 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004976 } // release lock
4977
4978 // Wake up poll loop since it may need to make new input dispatching choices.
4979 mLooper->wake();
4980}
4981
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004983 if (DEBUG_FOCUS) {
4984 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986
4987 bool changed;
4988 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004989 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990
4991 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4992 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004993 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 }
4995
4996 if (mDispatchEnabled && !enabled) {
4997 resetAndDropEverythingLocked("dispatcher is being disabled");
4998 }
4999
5000 mDispatchEnabled = enabled;
5001 mDispatchFrozen = frozen;
5002 changed = true;
5003 } else {
5004 changed = false;
5005 }
5006
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005007 if (DEBUG_FOCUS) {
5008 logDispatchStateLocked();
5009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010 } // release lock
5011
5012 if (changed) {
5013 // Wake up poll loop since it may need to make new input dispatching choices.
5014 mLooper->wake();
5015 }
5016}
5017
5018void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005019 if (DEBUG_FOCUS) {
5020 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022
5023 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005024 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025
5026 if (mInputFilterEnabled == enabled) {
5027 return;
5028 }
5029
5030 mInputFilterEnabled = enabled;
5031 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5032 } // release lock
5033
5034 // Wake up poll loop since there might be work to do to drop everything.
5035 mLooper->wake();
5036}
5037
Antonio Kanteka042c022022-07-06 16:51:07 -07005038bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5039 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005040 bool needWake = false;
5041 {
5042 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005043 ALOGD_IF(DEBUG_TOUCH_MODE,
5044 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5045 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5046 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5047 mTouchModePerDisplay.count(displayId) == 0
5048 ? "not set"
5049 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5050
Antonio Kantek15beb512022-06-13 22:35:41 +00005051 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5052 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005053 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005054 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005055 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005056 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5057 !recentWindowsAreOwnedByLocked(pid, uid)) {
5058 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5059 "window nor none of the previously interacted window",
5060 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005061 return false;
5062 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005063 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005064 mTouchModePerDisplay[displayId] = inTouchMode;
5065 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5066 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005067 needWake = enqueueInboundEventLocked(std::move(entry));
5068 } // release lock
5069
5070 if (needWake) {
5071 mLooper->wake();
5072 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005073 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005074}
5075
Antonio Kantek48710e42022-03-24 14:19:30 -07005076bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5077 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5078 if (focusedToken == nullptr) {
5079 return false;
5080 }
5081 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5082 return isWindowOwnedBy(windowHandle, pid, uid);
5083}
5084
5085bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5086 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5087 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5088 const sp<WindowInfoHandle> windowHandle =
5089 getWindowHandleLocked(connectionToken);
5090 return isWindowOwnedBy(windowHandle, pid, uid);
5091 }) != mInteractionConnectionTokens.end();
5092}
5093
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005094void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5095 if (opacity < 0 || opacity > 1) {
5096 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5097 return;
5098 }
5099
5100 std::scoped_lock lock(mLock);
5101 mMaximumObscuringOpacityForTouch = opacity;
5102}
5103
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005104std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5105InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005106 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5107 for (TouchedWindow& w : state.windows) {
5108 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005109 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005110 }
5111 }
5112 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005113 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005114}
5115
arthurhungb89ccb02020-12-30 16:19:01 +08005116bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5117 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005118 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005119 if (DEBUG_FOCUS) {
5120 ALOGD("Trivial transfer to same window.");
5121 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005122 return true;
5123 }
5124
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005126 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127
Arthur Hungabbb9d82021-09-01 14:52:30 +00005128 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005129 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005130 if (state == nullptr || touchedWindow == nullptr) {
5131 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 return false;
5133 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005134
Arthur Hungabbb9d82021-09-01 14:52:30 +00005135 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5136 if (toWindowHandle == nullptr) {
5137 ALOGW("Cannot transfer focus because to window not found.");
5138 return false;
5139 }
5140
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005141 if (DEBUG_FOCUS) {
5142 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005143 touchedWindow->windowHandle->getName().c_str(),
5144 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146
Arthur Hungabbb9d82021-09-01 14:52:30 +00005147 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005148 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005149 BitSet32 pointerIds = touchedWindow->pointerIds;
5150 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151
Arthur Hungabbb9d82021-09-01 14:52:30 +00005152 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005153 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005154 ftl::Flags<InputTarget::Flags> newTargetFlags =
5155 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005156 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005157 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005158 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005159 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160
Arthur Hungabbb9d82021-09-01 14:52:30 +00005161 // Store the dragging window.
5162 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005163 if (pointerIds.count() != 1) {
5164 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5165 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005166 return false;
5167 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005168 // Track the pointer id for drag window and generate the drag state.
5169 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005170 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 }
5172
Arthur Hungabbb9d82021-09-01 14:52:30 +00005173 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005174 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5175 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005176 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005177 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005178 CancelationOptions
5179 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5180 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005182 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 }
5184
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005185 if (DEBUG_FOCUS) {
5186 logDispatchStateLocked();
5187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 } // release lock
5189
5190 // Wake up poll loop since it may need to make new input dispatching choices.
5191 mLooper->wake();
5192 return true;
5193}
5194
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005195/**
5196 * Get the touched foreground window on the given display.
5197 * Return null if there are no windows touched on that display, or if more than one foreground
5198 * window is being touched.
5199 */
5200sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5201 auto stateIt = mTouchStatesByDisplay.find(displayId);
5202 if (stateIt == mTouchStatesByDisplay.end()) {
5203 ALOGI("No touch state on display %" PRId32, displayId);
5204 return nullptr;
5205 }
5206
5207 const TouchState& state = stateIt->second;
5208 sp<WindowInfoHandle> touchedForegroundWindow;
5209 // If multiple foreground windows are touched, return nullptr
5210 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005211 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005212 if (touchedForegroundWindow != nullptr) {
5213 ALOGI("Two or more foreground windows: %s and %s",
5214 touchedForegroundWindow->getName().c_str(),
5215 window.windowHandle->getName().c_str());
5216 return nullptr;
5217 }
5218 touchedForegroundWindow = window.windowHandle;
5219 }
5220 }
5221 return touchedForegroundWindow;
5222}
5223
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005224// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005225bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005226 sp<IBinder> fromToken;
5227 { // acquire lock
5228 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005229 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005230 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005231 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5232 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005233 return false;
5234 }
5235
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005236 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5237 if (from == nullptr) {
5238 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5239 return false;
5240 }
5241
5242 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005243 } // release lock
5244
5245 return transferTouchFocus(fromToken, destChannelToken);
5246}
5247
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005249 if (DEBUG_FOCUS) {
5250 ALOGD("Resetting and dropping all events (%s).", reason);
5251 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252
5253 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5254 synthesizeCancelationEventsForAllConnectionsLocked(options);
5255
5256 resetKeyRepeatLocked();
5257 releasePendingEventLocked();
5258 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005259 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005261 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005262 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005264 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265}
5266
5267void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005268 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 dumpDispatchStateLocked(dump);
5270
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005271 std::istringstream stream(dump);
5272 std::string line;
5273
5274 while (std::getline(stream, line, '\n')) {
5275 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 }
5277}
5278
Prabir Pradhan99987712020-11-10 18:43:05 -08005279std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5280 std::string dump;
5281
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005282 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5283 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005284
5285 std::string windowName = "None";
5286 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005287 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005288 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5289 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5290 : "token has capture without window";
5291 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005292 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005293
5294 return dump;
5295}
5296
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005297void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005298 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5299 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5300 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005301 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302
Tiger Huang721e26f2018-07-24 22:26:19 +08005303 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5304 dump += StringPrintf(INDENT "FocusedApplications:\n");
5305 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5306 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005307 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005308 const std::chrono::duration timeout =
5309 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005310 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005311 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005312 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005315 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005317
Vishnu Nairc519ff72021-01-21 08:23:08 -08005318 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005319 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005321 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005322 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005323 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005324 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5325 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 }
5327 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005328 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 }
5330
arthurhung6d4bed92021-03-17 11:59:33 +08005331 if (mDragState) {
5332 dump += StringPrintf(INDENT "DragState:\n");
5333 mDragState->dump(dump, INDENT2);
5334 }
5335
Arthur Hungb92218b2018-08-14 12:00:21 +08005336 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005337 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5338 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5339 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5340 const auto& displayInfo = it->second;
5341 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5342 displayInfo.logicalHeight);
5343 displayInfo.transform.dump(dump, "transform", INDENT4);
5344 } else {
5345 dump += INDENT2 "No DisplayInfo found!\n";
5346 }
5347
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005348 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005349 dump += INDENT2 "Windows:\n";
5350 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005351 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5352 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005354 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005355 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005356 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005357 "applicationInfo.name=%s, "
5358 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005359 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005360 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005361 windowInfo->displayId,
5362 windowInfo->inputConfig.string().c_str(),
5363 windowInfo->alpha, windowInfo->frameLeft,
5364 windowInfo->frameTop, windowInfo->frameRight,
5365 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005366 windowInfo->applicationInfo.name.c_str(),
5367 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005368 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005369 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005370 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005371 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005372 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005373 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005374 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005375 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005376 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005377 }
5378 } else {
5379 dump += INDENT2 "Windows: <none>\n";
5380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 }
5382 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005383 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 }
5385
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005386 if (!mGlobalMonitorsByDisplay.empty()) {
5387 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5388 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005389 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005392 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 }
5394
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005395 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396
5397 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005398 if (!mRecentQueue.empty()) {
5399 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005400 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005401 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005402 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005403 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 }
5405 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005406 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408
5409 // Dump event currently being dispatched.
5410 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005411 dump += INDENT "PendingEvent:\n";
5412 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005413 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005414 dump += StringPrintf(", age=%" PRId64 "ms\n",
5415 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005417 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418 }
5419
5420 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005421 if (!mInboundQueue.empty()) {
5422 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005423 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005424 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005425 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005426 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 }
5428 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
5431
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005432 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005433 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005434 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5435 const KeyReplacement& replacement = pair.first;
5436 int32_t newKeyCode = pair.second;
5437 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005438 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005439 }
5440 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005441 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005442 }
5443
Prabir Pradhancef936d2021-07-21 16:17:52 +00005444 if (!mCommandQueue.empty()) {
5445 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5446 } else {
5447 dump += INDENT "CommandQueue: <empty>\n";
5448 }
5449
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005450 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005451 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005452 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005453 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005454 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005455 connection->inputChannel->getFd().get(),
5456 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005457 connection->getWindowName().c_str(),
5458 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005459 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005461 if (!connection->outboundQueue.empty()) {
5462 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5463 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005464 dump += dumpQueue(connection->outboundQueue, currentTime);
5465
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005467 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 }
5469
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005470 if (!connection->waitQueue.empty()) {
5471 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5472 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005473 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005475 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
5477 }
5478 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005479 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 }
5481
5482 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005483 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5484 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005486 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487 }
5488
Antonio Kantek15beb512022-06-13 22:35:41 +00005489 if (!mTouchModePerDisplay.empty()) {
5490 dump += INDENT "TouchModePerDisplay:\n";
5491 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5492 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5493 std::to_string(touchMode).c_str());
5494 }
5495 } else {
5496 dump += INDENT "TouchModePerDisplay: <none>\n";
5497 }
5498
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005499 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005500 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5501 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5502 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005503 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005504 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505}
5506
Michael Wright3dd60e22019-03-27 22:06:44 +00005507void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5508 const size_t numMonitors = monitors.size();
5509 for (size_t i = 0; i < numMonitors; i++) {
5510 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005511 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005512 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5513 dump += "\n";
5514 }
5515}
5516
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005517class LooperEventCallback : public LooperCallback {
5518public:
5519 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5520 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5521
5522private:
5523 std::function<int(int events)> mCallback;
5524};
5525
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005526Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005527 if (DEBUG_CHANNEL_CREATION) {
5528 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005531 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005532 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005533 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005534
5535 if (result) {
5536 return base::Error(result) << "Failed to open input channel pair with name " << name;
5537 }
5538
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005540 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005541 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005542 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005543 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005544 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005546 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5547 ALOGE("Created a new connection, but the token %p is already known", token.get());
5548 }
5549 mConnectionsByToken.emplace(token, connection);
5550
5551 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5552 this, std::placeholders::_1, token);
5553
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005554 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5555 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 } // release lock
5557
5558 // Wake the looper because some connections have changed.
5559 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005560 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561}
5562
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005563Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005564 const std::string& name,
5565 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005566 std::shared_ptr<InputChannel> serverChannel;
5567 std::unique_ptr<InputChannel> clientChannel;
5568 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5569 if (result) {
5570 return base::Error(result) << "Failed to open input channel pair with name " << name;
5571 }
5572
Michael Wright3dd60e22019-03-27 22:06:44 +00005573 { // acquire lock
5574 std::scoped_lock _l(mLock);
5575
5576 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005577 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5578 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005579 }
5580
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005581 sp<Connection> connection =
5582 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005583 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005584 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005585
5586 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5587 ALOGE("Created a new connection, but the token %p is already known", token.get());
5588 }
5589 mConnectionsByToken.emplace(token, connection);
5590 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5591 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005592
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005593 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005594
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005595 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5596 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005597 }
Garfield Tan15601662020-09-22 15:32:38 -07005598
Michael Wright3dd60e22019-03-27 22:06:44 +00005599 // Wake the looper because some connections have changed.
5600 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005601 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005602}
5603
Garfield Tan15601662020-09-22 15:32:38 -07005604status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005606 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
Garfield Tan15601662020-09-22 15:32:38 -07005608 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 if (status) {
5610 return status;
5611 }
5612 } // release lock
5613
5614 // Wake the poll loop because removing the connection may have changed the current
5615 // synchronization state.
5616 mLooper->wake();
5617 return OK;
5618}
5619
Garfield Tan15601662020-09-22 15:32:38 -07005620status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5621 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005622 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005623 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005624 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 return BAD_VALUE;
5626 }
5627
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005628 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005629
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005631 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632 }
5633
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005634 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635
5636 nsecs_t currentTime = now();
5637 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5638
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005639 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 return OK;
5641}
5642
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005643void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005644 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5645 auto& [displayId, monitors] = *it;
5646 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5647 return monitor.inputChannel->getConnectionToken() == connectionToken;
5648 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005649
Michael Wright3dd60e22019-03-27 22:06:44 +00005650 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005651 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005652 } else {
5653 ++it;
5654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655 }
5656}
5657
Michael Wright3dd60e22019-03-27 22:06:44 +00005658status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005659 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005660 return pilferPointersLocked(token);
5661}
Michael Wright3dd60e22019-03-27 22:06:44 +00005662
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005663status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005664 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5665 if (!requestingChannel) {
5666 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5667 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005668 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005669
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005670 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005671 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005672 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5673 " Ignoring.");
5674 return BAD_VALUE;
5675 }
5676
5677 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005678 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005679 // Send cancel events to all the input channels we're stealing from.
5680 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5681 "input channel stole pointer stream");
5682 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005683 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005684 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005685 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005686 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005687 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005688 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005689 if (channel != nullptr && channel->getConnectionToken() != token) {
5690 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5691 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5692 canceledWindows += channel->getName();
5693 }
5694 }
5695 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5696 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5697 canceledWindows.c_str());
5698
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005699 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005700 // This only blocks relevant pointers to be sent to other windows
5701 window.isPilferingPointers = true;
5702
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005703 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005704 return OK;
5705}
5706
Prabir Pradhan99987712020-11-10 18:43:05 -08005707void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5708 { // acquire lock
5709 std::scoped_lock _l(mLock);
5710 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005711 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005712 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5713 windowHandle != nullptr ? windowHandle->getName().c_str()
5714 : "token without window");
5715 }
5716
Vishnu Nairc519ff72021-01-21 08:23:08 -08005717 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005718 if (focusedToken != windowToken) {
5719 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5720 enabled ? "enable" : "disable");
5721 return;
5722 }
5723
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005724 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005725 ALOGW("Ignoring request to %s Pointer Capture: "
5726 "window has %s requested pointer capture.",
5727 enabled ? "enable" : "disable", enabled ? "already" : "not");
5728 return;
5729 }
5730
Christine Franksb768bb42021-11-29 12:11:31 -08005731 if (enabled) {
5732 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5733 mIneligibleDisplaysForPointerCapture.end(),
5734 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5735 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5736 return;
5737 }
5738 }
5739
Prabir Pradhan99987712020-11-10 18:43:05 -08005740 setPointerCaptureLocked(enabled);
5741 } // release lock
5742
5743 // Wake the thread to process command entries.
5744 mLooper->wake();
5745}
5746
Christine Franksb768bb42021-11-29 12:11:31 -08005747void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5748 { // acquire lock
5749 std::scoped_lock _l(mLock);
5750 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5751 if (!isEligible) {
5752 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5753 }
5754 } // release lock
5755}
5756
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005757std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5758 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005759 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005760 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005761 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005762 }
5763 }
5764 }
5765 return std::nullopt;
5766}
5767
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005768sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005769 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005770 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005771 }
5772
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005773 for (const auto& [token, connection] : mConnectionsByToken) {
5774 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005775 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 }
5777 }
Robert Carr4e670e52018-08-15 13:26:12 -07005778
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005779 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780}
5781
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005782std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5783 sp<Connection> connection = getConnectionLocked(connectionToken);
5784 if (connection == nullptr) {
5785 return "<nullptr>";
5786 }
5787 return connection->getInputChannelName();
5788}
5789
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005790void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005791 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005792 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005793}
5794
Prabir Pradhancef936d2021-07-21 16:17:52 +00005795void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5796 const sp<Connection>& connection, uint32_t seq,
5797 bool handled, nsecs_t consumeTime) {
5798 // Handle post-event policy actions.
5799 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5800 if (dispatchEntryIt == connection->waitQueue.end()) {
5801 return;
5802 }
5803 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5804 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5805 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5806 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5807 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5808 }
5809 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5810 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5811 connection->inputChannel->getConnectionToken(),
5812 dispatchEntry->deliveryTime, consumeTime, finishTime);
5813 }
5814
5815 bool restartEvent;
5816 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5817 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5818 restartEvent =
5819 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5820 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5821 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5822 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5823 handled);
5824 } else {
5825 restartEvent = false;
5826 }
5827
5828 // Dequeue the event and start the next cycle.
5829 // Because the lock might have been released, it is possible that the
5830 // contents of the wait queue to have been drained, so we need to double-check
5831 // a few things.
5832 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5833 if (dispatchEntryIt != connection->waitQueue.end()) {
5834 dispatchEntry = *dispatchEntryIt;
5835 connection->waitQueue.erase(dispatchEntryIt);
5836 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5837 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5838 if (!connection->responsive) {
5839 connection->responsive = isConnectionResponsive(*connection);
5840 if (connection->responsive) {
5841 // The connection was unresponsive, and now it's responsive.
5842 processConnectionResponsiveLocked(*connection);
5843 }
5844 }
5845 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005846 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005847 connection->outboundQueue.push_front(dispatchEntry);
5848 traceOutboundQueueLength(*connection);
5849 } else {
5850 releaseDispatchEntry(dispatchEntry);
5851 }
5852 }
5853
5854 // Start the next dispatch cycle for this connection.
5855 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856}
5857
Prabir Pradhancef936d2021-07-21 16:17:52 +00005858void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5859 const sp<IBinder>& newToken) {
5860 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5861 scoped_unlock unlock(mLock);
5862 mPolicy->notifyFocusChanged(oldToken, newToken);
5863 };
5864 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865}
5866
Prabir Pradhancef936d2021-07-21 16:17:52 +00005867void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5868 auto command = [this, token, x, y]() REQUIRES(mLock) {
5869 scoped_unlock unlock(mLock);
5870 mPolicy->notifyDropWindow(token, x, y);
5871 };
5872 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005873}
5874
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005875void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5876 if (connection == nullptr) {
5877 LOG_ALWAYS_FATAL("Caller must check for nullness");
5878 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005879 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5880 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005881 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005882 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005883 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005884 return;
5885 }
5886 /**
5887 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5888 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5889 * has changed. This could cause newer entries to time out before the already dispatched
5890 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5891 * processes the events linearly. So providing information about the oldest entry seems to be
5892 * most useful.
5893 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005894 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005895 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5896 std::string reason =
5897 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005898 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005899 ns2ms(currentWait),
5900 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005901 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005902 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005903
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005904 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5905
5906 // Stop waking up for events on this connection, it is already unresponsive
5907 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005908}
5909
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005910void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5911 std::string reason =
5912 StringPrintf("%s does not have a focused window", application->getName().c_str());
5913 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005914
Prabir Pradhancef936d2021-07-21 16:17:52 +00005915 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5916 scoped_unlock unlock(mLock);
5917 mPolicy->notifyNoFocusedWindowAnr(application);
5918 };
5919 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005920}
5921
chaviw98318de2021-05-19 16:45:23 -05005922void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005923 const std::string& reason) {
5924 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5925 updateLastAnrStateLocked(windowLabel, reason);
5926}
5927
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005928void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5929 const std::string& reason) {
5930 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005931 updateLastAnrStateLocked(windowLabel, reason);
5932}
5933
5934void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5935 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005937 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 struct tm tm;
5939 localtime_r(&t, &tm);
5940 char timestr[64];
5941 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005942 mLastAnrState.clear();
5943 mLastAnrState += INDENT "ANR:\n";
5944 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005945 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5946 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005947 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948}
5949
Prabir Pradhancef936d2021-07-21 16:17:52 +00005950void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5951 KeyEntry& entry) {
5952 const KeyEvent event = createKeyEvent(entry);
5953 nsecs_t delay = 0;
5954 { // release lock
5955 scoped_unlock unlock(mLock);
5956 android::base::Timer t;
5957 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5958 entry.policyFlags);
5959 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5960 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5961 std::to_string(t.duration().count()).c_str());
5962 }
5963 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964
5965 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005966 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005967 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005968 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005969 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005970 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5971 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973}
5974
Prabir Pradhancef936d2021-07-21 16:17:52 +00005975void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005976 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005977 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005978 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005979 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005980 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005981 };
5982 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005983}
5984
Prabir Pradhanedd96402022-02-15 01:46:16 -08005985void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5986 std::optional<int32_t> pid) {
5987 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005988 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005989 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005990 };
5991 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005992}
5993
5994/**
5995 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5996 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5997 * command entry to the command queue.
5998 */
5999void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6000 std::string reason) {
6001 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006002 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006003 if (connection.monitor) {
6004 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6005 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006006 pid = findMonitorPidByTokenLocked(connectionToken);
6007 } else {
6008 // The connection is a window
6009 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6010 reason.c_str());
6011 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6012 if (handle != nullptr) {
6013 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006014 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006015 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006016 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006017}
6018
6019/**
6020 * Tell the policy that a connection has become responsive so that it can stop ANR.
6021 */
6022void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6023 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006024 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006025 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006026 pid = findMonitorPidByTokenLocked(connectionToken);
6027 } else {
6028 // The connection is a window
6029 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6030 if (handle != nullptr) {
6031 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006032 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006033 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006034 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006035}
6036
Prabir Pradhancef936d2021-07-21 16:17:52 +00006037bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006038 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006039 KeyEntry& keyEntry, bool handled) {
6040 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006041 if (!handled) {
6042 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006043 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006044 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006045 return false;
6046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006048 // Get the fallback key state.
6049 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006050 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006051 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 connection->inputState.removeFallbackKey(originalKeyCode);
6054 }
6055
6056 if (handled || !dispatchEntry->hasForegroundTarget()) {
6057 // If the application handles the original key for which we previously
6058 // generated a fallback or if the window is not a foreground window,
6059 // then cancel the associated fallback key, if any.
6060 if (fallbackKeyCode != -1) {
6061 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006062 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6063 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6064 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6065 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6066 keyEntry.policyFlags);
6067 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006068 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070
6071 mLock.unlock();
6072
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006073 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006074 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075
6076 mLock.lock();
6077
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006078 // Cancel the fallback key.
6079 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006081 "application handled the original non-fallback key "
6082 "or is no longer a foreground target, "
6083 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084 options.keyCode = fallbackKeyCode;
6085 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006087 connection->inputState.removeFallbackKey(originalKeyCode);
6088 }
6089 } else {
6090 // If the application did not handle a non-fallback key, first check
6091 // that we are in a good state to perform unhandled key event processing
6092 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006093 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006094 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006095 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6096 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6097 "since this is not an initial down. "
6098 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6099 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6100 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006101 return false;
6102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006104 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006105 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6106 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6107 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6108 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6109 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006110 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006111
6112 mLock.unlock();
6113
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006114 bool fallback =
6115 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006116 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006117
6118 mLock.lock();
6119
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006120 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006121 connection->inputState.removeFallbackKey(originalKeyCode);
6122 return false;
6123 }
6124
6125 // Latch the fallback keycode for this key on an initial down.
6126 // The fallback keycode cannot change at any other point in the lifecycle.
6127 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006129 fallbackKeyCode = event.getKeyCode();
6130 } else {
6131 fallbackKeyCode = AKEYCODE_UNKNOWN;
6132 }
6133 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6134 }
6135
6136 ALOG_ASSERT(fallbackKeyCode != -1);
6137
6138 // Cancel the fallback key if the policy decides not to send it anymore.
6139 // We will continue to dispatch the key to the policy but we will no
6140 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006141 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6142 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006143 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6144 if (fallback) {
6145 ALOGD("Unhandled key event: Policy requested to send key %d"
6146 "as a fallback for %d, but on the DOWN it had requested "
6147 "to send %d instead. Fallback canceled.",
6148 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6149 } else {
6150 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6151 "but on the DOWN it had requested to send %d. "
6152 "Fallback canceled.",
6153 originalKeyCode, fallbackKeyCode);
6154 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006155 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006156
6157 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6158 "canceling fallback, policy no longer desires it");
6159 options.keyCode = fallbackKeyCode;
6160 synthesizeCancelationEventsForConnectionLocked(connection, options);
6161
6162 fallback = false;
6163 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006164 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006165 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006166 }
6167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006168
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006169 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6170 {
6171 std::string msg;
6172 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6173 connection->inputState.getFallbackKeys();
6174 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6175 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6176 }
6177 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6178 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006180 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006181
6182 if (fallback) {
6183 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006184 keyEntry.eventTime = event.getEventTime();
6185 keyEntry.deviceId = event.getDeviceId();
6186 keyEntry.source = event.getSource();
6187 keyEntry.displayId = event.getDisplayId();
6188 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6189 keyEntry.keyCode = fallbackKeyCode;
6190 keyEntry.scanCode = event.getScanCode();
6191 keyEntry.metaState = event.getMetaState();
6192 keyEntry.repeatCount = event.getRepeatCount();
6193 keyEntry.downTime = event.getDownTime();
6194 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006195
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006196 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6197 ALOGD("Unhandled key event: Dispatching fallback key. "
6198 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6199 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6200 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006201 return true; // restart the event
6202 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006203 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6204 ALOGD("Unhandled key event: No fallback key.");
6205 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006206
6207 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006208 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006209 }
6210 }
6211 return false;
6212}
6213
Prabir Pradhancef936d2021-07-21 16:17:52 +00006214bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006215 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006216 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006217 return false;
6218}
6219
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220void InputDispatcher::traceInboundQueueLengthLocked() {
6221 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006222 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223 }
6224}
6225
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006226void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006227 if (ATRACE_ENABLED()) {
6228 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006229 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6230 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 }
6232}
6233
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006234void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 if (ATRACE_ENABLED()) {
6236 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006237 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6238 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 }
6240}
6241
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006242void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006243 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006245 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 dumpDispatchStateLocked(dump);
6247
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006248 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006249 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006250 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 }
6252}
6253
6254void InputDispatcher::monitor() {
6255 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006256 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006258 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259}
6260
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006261/**
6262 * Wake up the dispatcher and wait until it processes all events and commands.
6263 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6264 * this method can be safely called from any thread, as long as you've ensured that
6265 * the work you are interested in completing has already been queued.
6266 */
6267bool InputDispatcher::waitForIdle() {
6268 /**
6269 * Timeout should represent the longest possible time that a device might spend processing
6270 * events and commands.
6271 */
6272 constexpr std::chrono::duration TIMEOUT = 100ms;
6273 std::unique_lock lock(mLock);
6274 mLooper->wake();
6275 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6276 return result == std::cv_status::no_timeout;
6277}
6278
Vishnu Naire798b472020-07-23 13:52:21 -07006279/**
6280 * Sets focus to the window identified by the token. This must be called
6281 * after updating any input window handles.
6282 *
6283 * Params:
6284 * request.token - input channel token used to identify the window that should gain focus.
6285 * request.focusedToken - the token that the caller expects currently to be focused. If the
6286 * specified token does not match the currently focused window, this request will be dropped.
6287 * If the specified focused token matches the currently focused window, the call will succeed.
6288 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6289 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6290 * when requesting the focus change. This determines which request gets
6291 * precedence if there is a focus change request from another source such as pointer down.
6292 */
Vishnu Nair958da932020-08-21 17:12:37 -07006293void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6294 { // acquire lock
6295 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006296 std::optional<FocusResolver::FocusChanges> changes =
6297 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6298 if (changes) {
6299 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006300 }
6301 } // release lock
6302 // Wake up poll loop since it may need to make new input dispatching choices.
6303 mLooper->wake();
6304}
6305
Vishnu Nairc519ff72021-01-21 08:23:08 -08006306void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6307 if (changes.oldFocus) {
6308 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006309 if (focusedInputChannel) {
6310 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6311 "focus left window");
6312 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006313 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006314 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006315 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006316 if (changes.newFocus) {
6317 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006318 }
6319
Prabir Pradhan99987712020-11-10 18:43:05 -08006320 // If a window has pointer capture, then it must have focus. We need to ensure that this
6321 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6322 // If the window loses focus before it loses pointer capture, then the window can be in a state
6323 // where it has pointer capture but not focus, violating the contract. Therefore we must
6324 // dispatch the pointer capture event before the focus event. Since focus events are added to
6325 // the front of the queue (above), we add the pointer capture event to the front of the queue
6326 // after the focus events are added. This ensures the pointer capture event ends up at the
6327 // front.
6328 disablePointerCaptureForcedLocked();
6329
Vishnu Nairc519ff72021-01-21 08:23:08 -08006330 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006331 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006332 }
6333}
Vishnu Nair958da932020-08-21 17:12:37 -07006334
Prabir Pradhan99987712020-11-10 18:43:05 -08006335void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006336 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006337 return;
6338 }
6339
6340 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6341
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006342 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006343 setPointerCaptureLocked(false);
6344 }
6345
6346 if (!mWindowTokenWithPointerCapture) {
6347 // No need to send capture changes because no window has capture.
6348 return;
6349 }
6350
6351 if (mPendingEvent != nullptr) {
6352 // Move the pending event to the front of the queue. This will give the chance
6353 // for the pending event to be dropped if it is a captured event.
6354 mInboundQueue.push_front(mPendingEvent);
6355 mPendingEvent = nullptr;
6356 }
6357
6358 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006359 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006360 mInboundQueue.push_front(std::move(entry));
6361}
6362
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006363void InputDispatcher::setPointerCaptureLocked(bool enable) {
6364 mCurrentPointerCaptureRequest.enable = enable;
6365 mCurrentPointerCaptureRequest.seq++;
6366 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006367 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006368 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006369 };
6370 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006371}
6372
Vishnu Nair599f1412021-06-21 10:39:58 -07006373void InputDispatcher::displayRemoved(int32_t displayId) {
6374 { // acquire lock
6375 std::scoped_lock _l(mLock);
6376 // Set an empty list to remove all handles from the specific display.
6377 setInputWindowsLocked(/* window handles */ {}, displayId);
6378 setFocusedApplicationLocked(displayId, nullptr);
6379 // Call focus resolver to clean up stale requests. This must be called after input windows
6380 // have been removed for the removed display.
6381 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006382 // Reset pointer capture eligibility, regardless of previous state.
6383 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006384 // Remove the associated touch mode state.
6385 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006386 } // release lock
6387
6388 // Wake up poll loop since it may need to make new input dispatching choices.
6389 mLooper->wake();
6390}
6391
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006392void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6393 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006394 // The listener sends the windows as a flattened array. Separate the windows by display for
6395 // more convenient parsing.
6396 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006397 for (const auto& info : windowInfos) {
6398 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006399 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006400 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006401
6402 { // acquire lock
6403 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006404
6405 // Ensure that we have an entry created for all existing displays so that if a displayId has
6406 // no windows, we can tell that the windows were removed from the display.
6407 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6408 handlesPerDisplay[displayId];
6409 }
6410
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006411 mDisplayInfos.clear();
6412 for (const auto& displayInfo : displayInfos) {
6413 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6414 }
6415
6416 for (const auto& [displayId, handles] : handlesPerDisplay) {
6417 setInputWindowsLocked(handles, displayId);
6418 }
6419 }
6420 // Wake up poll loop since it may need to make new input dispatching choices.
6421 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006422}
6423
Vishnu Nair062a8672021-09-03 16:07:44 -07006424bool InputDispatcher::shouldDropInput(
6425 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006426 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6427 (windowHandle->getInfo()->inputConfig.test(
6428 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006429 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006430 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6431 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006432 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006433 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006434 windowHandle->getInfo()->displayId);
6435 return true;
6436 }
6437 return false;
6438}
6439
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006440void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6441 const std::vector<gui::WindowInfo>& windowInfos,
6442 const std::vector<DisplayInfo>& displayInfos) {
6443 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6444}
6445
Arthur Hungdfd528e2021-12-08 13:23:04 +00006446void InputDispatcher::cancelCurrentTouch() {
6447 {
6448 std::scoped_lock _l(mLock);
6449 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6450 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6451 "cancel current touch");
6452 synthesizeCancelationEventsForAllConnectionsLocked(options);
6453
6454 mTouchStatesByDisplay.clear();
6455 mLastHoverWindowHandle.clear();
6456 }
6457 // Wake up poll loop since there might be work to do.
6458 mLooper->wake();
6459}
6460
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006461void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6462 std::scoped_lock _l(mLock);
6463 mMonitorDispatchingTimeout = timeout;
6464}
6465
Garfield Tane84e6f92019-08-29 17:28:41 -07006466} // namespace android::inputdispatcher