blob: ac08acc5c87e895bd543490315a79c7fc645dd3f [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 }
Arthur Hung96483742022-11-15 03:30:48 +00002309
2310 // Update the pointerIds for non-splittable when it received pointer down.
2311 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2312 // If no split, we suppose all touched windows should receive pointer down.
2313 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2314 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2315 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2316 // Ignore drag window for it should just track one pointer.
2317 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2318 continue;
2319 }
2320 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2321 }
2322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 }
2324
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002325 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002327 // Let the previous window know that the hover sequence is over, unless we already did
2328 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002329 if (mLastHoverWindowHandle != nullptr &&
2330 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2331 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002332 if (DEBUG_HOVER) {
2333 ALOGD("Sending hover exit event to window %s.",
2334 mLastHoverWindowHandle->getName().c_str());
2335 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002337 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2338 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340
Garfield Tandf26e862020-07-01 20:18:19 -07002341 // Let the new window know that the hover sequence is starting, unless we already did it
2342 // when dispatching it as is to newTouchedWindowHandle.
2343 if (newHoverWindowHandle != nullptr &&
2344 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2345 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002346 if (DEBUG_HOVER) {
2347 ALOGD("Sending hover enter event to window %s.",
2348 newHoverWindowHandle->getName().c_str());
2349 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002350 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002351 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002352 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 }
2354 }
2355
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002356 // Ensure that we have at least one foreground window or at least one window that cannot be a
2357 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2358 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2359 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002360 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2361 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002362 return !canReceiveForegroundTouches(
2363 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002364 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002365 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002366 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2367 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002368 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002369 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371
Prabir Pradhan5735a322022-04-11 17:23:34 +00002372 // Ensure that all touched windows are valid for injection.
2373 if (entry.injectionState != nullptr) {
2374 std::string errs;
2375 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002376 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002377 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2378 // dispatched to any uid, since the coords will be zeroed out later.
2379 continue;
2380 }
2381 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2382 if (err) errs += "\n - " + *err;
2383 }
2384 if (!errs.empty()) {
2385 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2386 "%d:%s",
2387 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002388 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002389 goto Failed;
2390 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002391 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 // Check whether windows listening for outside touches are owned by the same UID. If it is
2394 // set the policy flag that we will not reveal coordinate information to this window.
2395 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002396 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002397 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002398 if (foregroundWindowHandle) {
2399 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002400 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002401 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002402 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2403 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2404 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002405 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002406 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
2409 }
2410 }
2411 }
2412
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 // If this is the first pointer going down and the touched window has a wallpaper
2414 // then also add the touched wallpaper windows so they are locked in for the duration
2415 // of the touch gesture.
2416 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2417 // engine only supports touch events. We would need to add a mechanism similar
2418 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2419 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002420 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002421 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002422 if (foregroundWindowHandle &&
2423 foregroundWindowHandle->getInfo()->inputConfig.test(
2424 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002425 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002426 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002427 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2428 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002430 windowHandle->getInfo()->inputConfig.test(
2431 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002432 tempTouchState.addOrUpdateWindow(windowHandle,
2433 InputTarget::Flags::WINDOW_IS_OBSCURED |
2434 InputTarget::Flags::
2435 WINDOW_IS_PARTIALLY_OBSCURED |
2436 InputTarget::Flags::DISPATCH_AS_IS,
2437 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 }
2439 }
2440 }
2441 }
2442
2443 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002444 touchedWindows = tempTouchState.windows;
2445 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446
2447 // Drop the outside or hover touch windows since we will not care about them
2448 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002449 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450
2451Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002453 if (switchedDevice) {
2454 if (DEBUG_FOCUS) {
2455 ALOGD("Conflicting pointer actions: Switched to a different device.");
2456 }
2457 *outConflictingPointerActions = true;
2458 }
2459
2460 if (isHoverAction) {
2461 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002462 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002463 ALOGD_IF(DEBUG_FOCUS,
2464 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002465 *outConflictingPointerActions = true;
2466 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002467 tempTouchState.reset();
2468 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2469 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2470 tempTouchState.deviceId = entry.deviceId;
2471 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002472 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002473 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2474 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2475 // All pointers up or canceled.
2476 tempTouchState.reset();
2477 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2478 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002479 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002480 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002481 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002482 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002483 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2484 // One pointer went up.
2485 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2486 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002488 for (size_t i = 0; i < tempTouchState.windows.size();) {
2489 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2490 touchedWindow.pointerIds.clearBit(pointerId);
2491 if (touchedWindow.pointerIds.isEmpty()) {
2492 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2493 continue;
2494 }
2495 i += 1;
2496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 }
2498
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002499 // Save changes unless the action was scroll in which case the temporary touch
2500 // state was only valid for this one action.
2501 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002502 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002503 mTouchStatesByDisplay[displayId] = tempTouchState;
2504 } else {
2505 mTouchStatesByDisplay.erase(displayId);
2506 }
2507 }
2508
2509 // Update hover state.
2510 mLastHoverWindowHandle = newHoverWindowHandle;
2511
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002512 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513}
2514
arthurhung6d4bed92021-03-17 11:59:33 +08002515void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002516 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2517 // have an explicit reason to support it.
2518 constexpr bool isStylus = false;
2519
chaviw98318de2021-05-19 16:45:23 -05002520 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002521 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002522 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002523 if (dropWindow) {
2524 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002525 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002526 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002527 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002528 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002529 }
2530 mDragState.reset();
2531}
2532
2533void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002534 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002535 return;
2536 }
2537
arthurhung6d4bed92021-03-17 11:59:33 +08002538 if (!mDragState->isStartDrag) {
2539 mDragState->isStartDrag = true;
2540 mDragState->isStylusButtonDownAtStart =
2541 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2542 }
2543
Arthur Hung54745652022-04-20 07:17:41 +00002544 // Find the pointer index by id.
2545 int32_t pointerIndex = 0;
2546 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2547 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2548 if (pointerProperties.id == mDragState->pointerId) {
2549 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002550 }
Arthur Hung54745652022-04-20 07:17:41 +00002551 }
arthurhung6d4bed92021-03-17 11:59:33 +08002552
Arthur Hung54745652022-04-20 07:17:41 +00002553 if (uint32_t(pointerIndex) == entry.pointerCount) {
2554 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002555 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002556 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002557 return;
2558 }
2559
2560 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2561 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2562 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2563
2564 switch (maskedAction) {
2565 case AMOTION_EVENT_ACTION_MOVE: {
2566 // Handle the special case : stylus button no longer pressed.
2567 bool isStylusButtonDown =
2568 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2569 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2570 finishDragAndDrop(entry.displayId, x, y);
2571 return;
2572 }
2573
2574 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2575 // until we have an explicit reason to support it.
2576 constexpr bool isStylus = false;
2577
2578 const sp<WindowInfoHandle> hoverWindowHandle =
2579 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2580 isStylus, false /*addOutsideTargets*/,
2581 true /*ignoreDragWindow*/);
2582 // enqueue drag exit if needed.
2583 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2584 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2585 if (mDragState->dragHoverWindowHandle != nullptr) {
2586 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2587 y);
2588 }
2589 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2590 }
2591 // enqueue drag location if needed.
2592 if (hoverWindowHandle != nullptr) {
2593 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2594 }
2595 break;
2596 }
2597
2598 case AMOTION_EVENT_ACTION_POINTER_UP:
2599 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2600 break;
2601 }
2602 // The drag pointer is up.
2603 [[fallthrough]];
2604 case AMOTION_EVENT_ACTION_UP:
2605 finishDragAndDrop(entry.displayId, x, y);
2606 break;
2607 case AMOTION_EVENT_ACTION_CANCEL: {
2608 ALOGD("Receiving cancel when drag and drop.");
2609 sendDropWindowCommandLocked(nullptr, 0, 0);
2610 mDragState.reset();
2611 break;
2612 }
arthurhungb89ccb02020-12-30 16:19:01 +08002613 }
2614}
2615
chaviw98318de2021-05-19 16:45:23 -05002616void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002617 ftl::Flags<InputTarget::Flags> targetFlags,
2618 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002619 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002620 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002621 std::vector<InputTarget>::iterator it =
2622 std::find_if(inputTargets.begin(), inputTargets.end(),
2623 [&windowHandle](const InputTarget& inputTarget) {
2624 return inputTarget.inputChannel->getConnectionToken() ==
2625 windowHandle->getToken();
2626 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002627
chaviw98318de2021-05-19 16:45:23 -05002628 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002629
2630 if (it == inputTargets.end()) {
2631 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002632 std::shared_ptr<InputChannel> inputChannel =
2633 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002634 if (inputChannel == nullptr) {
2635 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2636 return;
2637 }
2638 inputTarget.inputChannel = inputChannel;
2639 inputTarget.flags = targetFlags;
2640 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002641 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002642 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2643 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002644 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002645 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002646 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002647 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002648 inputTargets.push_back(inputTarget);
2649 it = inputTargets.end() - 1;
2650 }
2651
2652 ALOG_ASSERT(it->flags == targetFlags);
2653 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2654
chaviw1ff3d1e2020-07-01 15:53:47 -07002655 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656}
2657
Michael Wright3dd60e22019-03-27 22:06:44 +00002658void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002659 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002660 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2661 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002662
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002663 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2664 InputTarget target;
2665 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002666 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002667 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2668 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002669 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2670 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002671 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002672 target.setDefaultPointerTransform(target.displayTransform);
2673 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 }
2675}
2676
Robert Carrc9bf1d32020-04-13 17:21:08 -07002677/**
2678 * Indicate whether one window handle should be considered as obscuring
2679 * another window handle. We only check a few preconditions. Actually
2680 * checking the bounds is left to the caller.
2681 */
chaviw98318de2021-05-19 16:45:23 -05002682static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2683 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002684 // Compare by token so cloned layers aren't counted
2685 if (haveSameToken(windowHandle, otherHandle)) {
2686 return false;
2687 }
2688 auto info = windowHandle->getInfo();
2689 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002690 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002691 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002692 } else if (otherInfo->alpha == 0 &&
2693 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002694 // Those act as if they were invisible, so we don't need to flag them.
2695 // We do want to potentially flag touchable windows even if they have 0
2696 // opacity, since they can consume touches and alter the effects of the
2697 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002698 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002699 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2700 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002701 } else if (info->ownerUid == otherInfo->ownerUid) {
2702 // If ownerUid is the same we don't generate occlusion events as there
2703 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002704 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002705 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002706 return false;
2707 } else if (otherInfo->displayId != info->displayId) {
2708 return false;
2709 }
2710 return true;
2711}
2712
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002713/**
2714 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2715 * untrusted, one should check:
2716 *
2717 * 1. If result.hasBlockingOcclusion is true.
2718 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2719 * BLOCK_UNTRUSTED.
2720 *
2721 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2722 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2723 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2724 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2725 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2726 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2727 *
2728 * If neither of those is true, then it means the touch can be allowed.
2729 */
2730InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002731 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2732 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002733 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002734 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002735 TouchOcclusionInfo info;
2736 info.hasBlockingOcclusion = false;
2737 info.obscuringOpacity = 0;
2738 info.obscuringUid = -1;
2739 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002740 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002741 if (windowHandle == otherHandle) {
2742 break; // All future windows are below us. Exit early.
2743 }
chaviw98318de2021-05-19 16:45:23 -05002744 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002745 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2746 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002747 if (DEBUG_TOUCH_OCCLUSION) {
2748 info.debugInfo.push_back(
2749 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2750 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002751 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2752 // we perform the checks below to see if the touch can be propagated or not based on the
2753 // window's touch occlusion mode
2754 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2755 info.hasBlockingOcclusion = true;
2756 info.obscuringUid = otherInfo->ownerUid;
2757 info.obscuringPackage = otherInfo->packageName;
2758 break;
2759 }
2760 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2761 uint32_t uid = otherInfo->ownerUid;
2762 float opacity =
2763 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2764 // Given windows A and B:
2765 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2766 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2767 opacityByUid[uid] = opacity;
2768 if (opacity > info.obscuringOpacity) {
2769 info.obscuringOpacity = opacity;
2770 info.obscuringUid = uid;
2771 info.obscuringPackage = otherInfo->packageName;
2772 }
2773 }
2774 }
2775 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002776 if (DEBUG_TOUCH_OCCLUSION) {
2777 info.debugInfo.push_back(
2778 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2779 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002780 return info;
2781}
2782
chaviw98318de2021-05-19 16:45:23 -05002783std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002784 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002785 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2786 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2787 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2788 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002789 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2790 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2791 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2792 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2793 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002794 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002795 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002796}
2797
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002798bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2799 if (occlusionInfo.hasBlockingOcclusion) {
2800 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2801 occlusionInfo.obscuringUid);
2802 return false;
2803 }
2804 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2805 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2806 "%.2f, maximum allowed = %.2f)",
2807 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2808 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2809 return false;
2810 }
2811 return true;
2812}
2813
chaviw98318de2021-05-19 16:45:23 -05002814bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002815 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002817 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2818 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002819 if (windowHandle == otherHandle) {
2820 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 }
chaviw98318de2021-05-19 16:45:23 -05002822 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002823 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002824 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 return true;
2826 }
2827 }
2828 return false;
2829}
2830
chaviw98318de2021-05-19 16:45:23 -05002831bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002832 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002833 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2834 const WindowInfo* windowInfo = windowHandle->getInfo();
2835 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002836 if (windowHandle == otherHandle) {
2837 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002838 }
chaviw98318de2021-05-19 16:45:23 -05002839 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002840 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002841 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002842 return true;
2843 }
2844 }
2845 return false;
2846}
2847
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002848std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002849 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002850 if (applicationHandle != nullptr) {
2851 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002852 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 } else {
2854 return applicationHandle->getName();
2855 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002856 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002857 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002859 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 }
2861}
2862
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002863void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002864 if (!isUserActivityEvent(eventEntry)) {
2865 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002866 return;
2867 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002868 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002869 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002870 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002871 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002872 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002873 if (DEBUG_DISPATCH_CYCLE) {
2874 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 return;
2877 }
2878 }
2879
2880 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002881 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002882 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002883 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2884 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 return;
2886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002888 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 eventType = USER_ACTIVITY_EVENT_TOUCH;
2890 }
2891 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002893 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2895 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 return;
2897 }
2898 eventType = USER_ACTIVITY_EVENT_BUTTON;
2899 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002901 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002902 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002903 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002904 break;
2905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 }
2907
Prabir Pradhancef936d2021-07-21 16:17:52 +00002908 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2909 REQUIRES(mLock) {
2910 scoped_unlock unlock(mLock);
2911 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2912 };
2913 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914}
2915
2916void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002918 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002919 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002920 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002922 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002923 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002924 ATRACE_NAME(message.c_str());
2925 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002926 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002927 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002928 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002929 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002930 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2931 inputTarget.getPointerInfoString().c_str());
2932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933
2934 // Skip this event if the connection status is not normal.
2935 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002936 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002937 if (DEBUG_DISPATCH_CYCLE) {
2938 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002939 connection->getInputChannelName().c_str(),
2940 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 return;
2943 }
2944
2945 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002946 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002947 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002948 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002949 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002951 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002952 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002953 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2954 "Splitting motion events requires a down time to be set for the "
2955 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002956 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002957 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2958 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 if (!splitMotionEntry) {
2960 return; // split event was dropped
2961 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002962 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2963 std::string reason = std::string("reason=pointer cancel on split window");
2964 android_log_event_list(LOGTAG_INPUT_CANCEL)
2965 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2966 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002967 if (DEBUG_FOCUS) {
2968 ALOGD("channel '%s' ~ Split motion event.",
2969 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002970 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002971 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002972 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2973 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 return;
2975 }
2976 }
2977
2978 // Not splitting. Enqueue dispatch entries for the event as is.
2979 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2980}
2981
2982void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002984 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002985 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002986 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002988 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002989 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002990 ATRACE_NAME(message.c_str());
2991 }
2992
hongzuo liu95785e22022-09-06 02:51:35 +00002993 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994
2995 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002996 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002997 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002998 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002999 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003000 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003001 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003002 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003003 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003004 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003005 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003006 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003007 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008
3009 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003010 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 startDispatchCycleLocked(currentTime, connection);
3012 }
3013}
3014
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003016 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003017 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003018 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003019 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003020 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3021 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003022 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003023 ATRACE_NAME(message.c_str());
3024 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003025 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3026 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 return;
3028 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003029
3030 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3031 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032
3033 // This is a new event.
3034 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003035 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003036 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003038 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3039 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003040 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003042 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003043 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003044 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003045 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003046 dispatchEntry->resolvedAction = keyEntry.action;
3047 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003049 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3050 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003051 if (DEBUG_DISPATCH_CYCLE) {
3052 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3053 "event",
3054 connection->getInputChannelName().c_str());
3055 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003056 return; // skip the inconsistent event
3057 }
3058 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003061 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003062 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003063 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3064 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3065 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3066 static_cast<int32_t>(IdGenerator::Source::OTHER);
3067 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003068 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003070 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003071 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003072 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003073 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003074 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003076 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3078 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003079 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003080 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 }
3082 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003083 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3084 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003085 if (DEBUG_DISPATCH_CYCLE) {
3086 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3087 "enter event",
3088 connection->getInputChannelName().c_str());
3089 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003090 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3091 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003095 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003096 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003097 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3098 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003099 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3104 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003105 if (DEBUG_DISPATCH_CYCLE) {
3106 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3107 "event",
3108 connection->getInputChannelName().c_str());
3109 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 return; // skip the inconsistent event
3111 }
3112
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003113 dispatchEntry->resolvedEventId =
3114 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3115 ? mIdGenerator.nextId()
3116 : motionEntry.id;
3117 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3118 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3119 ") to MotionEvent(id=0x%" PRIx32 ").",
3120 motionEntry.id, dispatchEntry->resolvedEventId);
3121 ATRACE_NAME(message.c_str());
3122 }
3123
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003124 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3125 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3126 // Skip reporting pointer down outside focus to the policy.
3127 break;
3128 }
3129
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003130 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003131 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132
3133 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003135 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003136 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003137 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3138 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003139 break;
3140 }
Chris Yef59a2f42020-10-16 12:55:26 -07003141 case EventEntry::Type::SENSOR: {
3142 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3143 break;
3144 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003145 case EventEntry::Type::CONFIGURATION_CHANGED:
3146 case EventEntry::Type::DEVICE_RESET: {
3147 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003148 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003149 break;
3150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
3152
3153 // Remember that we are waiting for this dispatch to complete.
3154 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003155 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 }
3157
3158 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003159 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003160 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003161}
3162
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003163/**
3164 * This function is purely for debugging. It helps us understand where the user interaction
3165 * was taking place. For example, if user is touching launcher, we will see a log that user
3166 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3167 * We will see both launcher and wallpaper in that list.
3168 * Once the interaction with a particular set of connections starts, no new logs will be printed
3169 * until the set of interacted connections changes.
3170 *
3171 * The following items are skipped, to reduce the logspam:
3172 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3173 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3174 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3175 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3176 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003177 */
3178void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3179 const std::vector<InputTarget>& targets) {
3180 // Skip ACTION_UP events, and all events other than keys and motions
3181 if (entry.type == EventEntry::Type::KEY) {
3182 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3183 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3184 return;
3185 }
3186 } else if (entry.type == EventEntry::Type::MOTION) {
3187 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3188 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3189 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3190 return;
3191 }
3192 } else {
3193 return; // Not a key or a motion
3194 }
3195
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003196 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003197 std::vector<sp<Connection>> newConnections;
3198 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003200 continue; // Skip windows that receive ACTION_OUTSIDE
3201 }
3202
3203 sp<IBinder> token = target.inputChannel->getConnectionToken();
3204 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003205 if (connection == nullptr) {
3206 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003207 }
3208 newConnectionTokens.insert(std::move(token));
3209 newConnections.emplace_back(connection);
3210 }
3211 if (newConnectionTokens == mInteractionConnectionTokens) {
3212 return; // no change
3213 }
3214 mInteractionConnectionTokens = newConnectionTokens;
3215
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003216 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003217 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003218 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003219 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003220 std::string message = "Interaction with: " + targetList;
3221 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003222 message += "<none>";
3223 }
3224 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3225}
3226
chaviwfd6d3512019-03-25 13:23:49 -07003227void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003228 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003229 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003230 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3231 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003232 return;
3233 }
3234
Vishnu Nairc519ff72021-01-21 08:23:08 -08003235 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003236 if (focusedToken == token) {
3237 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003238 return;
3239 }
3240
Prabir Pradhancef936d2021-07-21 16:17:52 +00003241 auto command = [this, token]() REQUIRES(mLock) {
3242 scoped_unlock unlock(mLock);
3243 mPolicy->onPointerDownOutsideFocus(token);
3244 };
3245 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246}
3247
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003248status_t InputDispatcher::publishMotionEvent(Connection& connection,
3249 DispatchEntry& dispatchEntry) const {
3250 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3251 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3252
3253 PointerCoords scaledCoords[MAX_POINTERS];
3254 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3255
3256 // Set the X and Y offset and X and Y scale depending on the input source.
3257 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003258 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003259 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3260 if (globalScaleFactor != 1.0f) {
3261 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3262 scaledCoords[i] = motionEntry.pointerCoords[i];
3263 // Don't apply window scale here since we don't want scale to affect raw
3264 // coordinates. The scale will be sent back to the client and applied
3265 // later when requesting relative coordinates.
3266 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3267 1 /* windowYScale */);
3268 }
3269 usingCoords = scaledCoords;
3270 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003271 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003272 // We don't want the dispatch target to know the coordinates
3273 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3274 scaledCoords[i].clear();
3275 }
3276 usingCoords = scaledCoords;
3277 }
3278
3279 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3280
3281 // Publish the motion event.
3282 return connection.inputPublisher
3283 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3284 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3285 std::move(hmac), dispatchEntry.resolvedAction,
3286 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3287 motionEntry.edgeFlags, motionEntry.metaState,
3288 motionEntry.buttonState, motionEntry.classification,
3289 dispatchEntry.transform, motionEntry.xPrecision,
3290 motionEntry.yPrecision, motionEntry.xCursorPosition,
3291 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3292 motionEntry.downTime, motionEntry.eventTime,
3293 motionEntry.pointerCount, motionEntry.pointerProperties,
3294 usingCoords);
3295}
3296
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003299 if (ATRACE_ENABLED()) {
3300 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003302 ATRACE_NAME(message.c_str());
3303 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003304 if (DEBUG_DISPATCH_CYCLE) {
3305 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003308 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003309 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003311 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003312 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313
3314 // Publish the event.
3315 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3317 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003318 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003319 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3320 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003323 status = connection->inputPublisher
3324 .publishKeyEvent(dispatchEntry->seq,
3325 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3326 keyEntry.source, keyEntry.displayId,
3327 std::move(hmac), dispatchEntry->resolvedAction,
3328 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3329 keyEntry.scanCode, keyEntry.metaState,
3330 keyEntry.repeatCount, keyEntry.downTime,
3331 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
3334
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003335 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003336 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 break;
3338 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003339
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003340 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003341 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003342 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003343 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003344 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003345 break;
3346 }
3347
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003348 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3349 const TouchModeEntry& touchModeEntry =
3350 static_cast<const TouchModeEntry&>(eventEntry);
3351 status = connection->inputPublisher
3352 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3353 touchModeEntry.inTouchMode);
3354
3355 break;
3356 }
3357
Prabir Pradhan99987712020-11-10 18:43:05 -08003358 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3359 const auto& captureEntry =
3360 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3361 status = connection->inputPublisher
3362 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003363 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003364 break;
3365 }
3366
arthurhungb89ccb02020-12-30 16:19:01 +08003367 case EventEntry::Type::DRAG: {
3368 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3369 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3370 dragEntry.id, dragEntry.x,
3371 dragEntry.y,
3372 dragEntry.isExiting);
3373 break;
3374 }
3375
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003376 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003377 case EventEntry::Type::DEVICE_RESET:
3378 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003379 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003380 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003381 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
3384
3385 // Check the result.
3386 if (status) {
3387 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003388 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390 "This is unexpected because the wait queue is empty, so the pipe "
3391 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003392 "event to it, status=%s(%d)",
3393 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3394 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3396 } else {
3397 // Pipe is full and we are waiting for the app to finish process some events
3398 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003399 if (DEBUG_DISPATCH_CYCLE) {
3400 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3401 "waiting for the application to catch up",
3402 connection->getInputChannelName().c_str());
3403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 }
3405 } else {
3406 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003407 "status=%s(%d)",
3408 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3409 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3411 }
3412 return;
3413 }
3414
3415 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003416 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3417 connection->outboundQueue.end(),
3418 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003419 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003420 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003421 if (connection->responsive) {
3422 mAnrTracker.insert(dispatchEntry->timeoutTime,
3423 connection->inputChannel->getConnectionToken());
3424 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003425 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
3427}
3428
chaviw09c8d2d2020-08-24 15:48:26 -07003429std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3430 size_t size;
3431 switch (event.type) {
3432 case VerifiedInputEvent::Type::KEY: {
3433 size = sizeof(VerifiedKeyEvent);
3434 break;
3435 }
3436 case VerifiedInputEvent::Type::MOTION: {
3437 size = sizeof(VerifiedMotionEvent);
3438 break;
3439 }
3440 }
3441 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3442 return mHmacKeyManager.sign(start, size);
3443}
3444
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003445const std::array<uint8_t, 32> InputDispatcher::getSignature(
3446 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003447 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3448 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003449 // Only sign events up and down events as the purely move events
3450 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003451 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003452 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003453
3454 VerifiedMotionEvent verifiedEvent =
3455 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3456 verifiedEvent.actionMasked = actionMasked;
3457 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3458 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003459}
3460
3461const std::array<uint8_t, 32> InputDispatcher::getSignature(
3462 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3463 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3464 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3465 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003466 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003467}
3468
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003471 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003472 if (DEBUG_DISPATCH_CYCLE) {
3473 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3474 connection->getInputChannelName().c_str(), seq, toString(handled));
3475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003477 if (connection->status == Connection::Status::BROKEN ||
3478 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 return;
3480 }
3481
3482 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003483 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3484 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3485 };
3486 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487}
3488
3489void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003490 const sp<Connection>& connection,
3491 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003492 if (DEBUG_DISPATCH_CYCLE) {
3493 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3494 connection->getInputChannelName().c_str(), toString(notify));
3495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496
3497 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003498 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003499 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003500 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003501 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
3503 // The connection appears to be unrecoverably broken.
3504 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003505 if (connection->status == Connection::Status::NORMAL) {
3506 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
3508 if (notify) {
3509 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003510 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3511 connection->getInputChannelName().c_str());
3512
3513 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003514 scoped_unlock unlock(mLock);
3515 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3516 };
3517 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
3519 }
3520}
3521
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003522void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3523 while (!queue.empty()) {
3524 DispatchEntry* dispatchEntry = queue.front();
3525 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003526 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528}
3529
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003530void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003532 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534 delete dispatchEntry;
3535}
3536
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003537int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3538 std::scoped_lock _l(mLock);
3539 sp<Connection> connection = getConnectionLocked(connectionToken);
3540 if (connection == nullptr) {
3541 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3542 connectionToken.get(), events);
3543 return 0; // remove the callback
3544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003546 bool notify;
3547 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3548 if (!(events & ALOOPER_EVENT_INPUT)) {
3549 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3550 "events=0x%x",
3551 connection->getInputChannelName().c_str(), events);
3552 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 }
3554
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003555 nsecs_t currentTime = now();
3556 bool gotOne = false;
3557 status_t status = OK;
3558 for (;;) {
3559 Result<InputPublisher::ConsumerResponse> result =
3560 connection->inputPublisher.receiveConsumerResponse();
3561 if (!result.ok()) {
3562 status = result.error().code();
3563 break;
3564 }
3565
3566 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3567 const InputPublisher::Finished& finish =
3568 std::get<InputPublisher::Finished>(*result);
3569 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3570 finish.consumeTime);
3571 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003572 if (shouldReportMetricsForConnection(*connection)) {
3573 const InputPublisher::Timeline& timeline =
3574 std::get<InputPublisher::Timeline>(*result);
3575 mLatencyTracker
3576 .trackGraphicsLatency(timeline.inputEventId,
3577 connection->inputChannel->getConnectionToken(),
3578 std::move(timeline.graphicsTimeline));
3579 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003580 }
3581 gotOne = true;
3582 }
3583 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003584 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003585 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 return 1;
3587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 }
3589
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003590 notify = status != DEAD_OBJECT || !connection->monitor;
3591 if (notify) {
3592 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3593 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3594 status);
3595 }
3596 } else {
3597 // Monitor channels are never explicitly unregistered.
3598 // We do it automatically when the remote endpoint is closed so don't warn about them.
3599 const bool stillHaveWindowHandle =
3600 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3601 notify = !connection->monitor && stillHaveWindowHandle;
3602 if (notify) {
3603 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3604 connection->getInputChannelName().c_str(), events);
3605 }
3606 }
3607
3608 // Remove the channel.
3609 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3610 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611}
3612
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003613void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003615 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003616 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618}
3619
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003620void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003621 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003622 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003623 for (const Monitor& monitor : monitors) {
3624 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003625 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003626 }
3627}
3628
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003630 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003631 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003632 if (connection == nullptr) {
3633 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003635
3636 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637}
3638
3639void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3640 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003641 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 return;
3643 }
3644
3645 nsecs_t currentTime = now();
3646
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003647 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003648 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003650 if (cancelationEvents.empty()) {
3651 return;
3652 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003653 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3654 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3655 "with reality: %s, mode=%d.",
3656 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3657 options.mode);
3658 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003659
Arthur Hungb3307ee2021-10-14 10:57:37 +00003660 std::string reason = std::string("reason=").append(options.reason);
3661 android_log_event_list(LOGTAG_INPUT_CANCEL)
3662 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3663
Svet Ganov5d3bc372020-01-26 23:11:07 -08003664 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003665 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003666 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3667 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003668 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003669 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 target.globalScaleFactor = windowInfo->globalScaleFactor;
3671 }
3672 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003673 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003674
hongzuo liu95785e22022-09-06 02:51:35 +00003675 const bool wasEmpty = connection->outboundQueue.empty();
3676
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003677 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003678 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003679 switch (cancelationEventEntry->type) {
3680 case EventEntry::Type::KEY: {
3681 logOutboundKeyDetails("cancel - ",
3682 static_cast<const KeyEntry&>(*cancelationEventEntry));
3683 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003685 case EventEntry::Type::MOTION: {
3686 logOutboundMotionDetails("cancel - ",
3687 static_cast<const MotionEntry&>(*cancelationEventEntry));
3688 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003690 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003691 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003692 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3693 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003694 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003695 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003696 break;
3697 }
3698 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003699 case EventEntry::Type::DEVICE_RESET:
3700 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003701 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003702 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003703 break;
3704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 }
3706
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003707 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003708 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003710
hongzuo liu95785e22022-09-06 02:51:35 +00003711 // If the outbound queue was previously empty, start the dispatch cycle going.
3712 if (wasEmpty && !connection->outboundQueue.empty()) {
3713 startDispatchCycleLocked(currentTime, connection);
3714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715}
3716
Svet Ganov5d3bc372020-01-26 23:11:07 -08003717void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003718 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003719 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720 return;
3721 }
3722
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003723 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003724 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003725
3726 if (downEvents.empty()) {
3727 return;
3728 }
3729
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003730 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3732 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003733 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003734
3735 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003736 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003737 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3738 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003739 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003740 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003741 target.globalScaleFactor = windowInfo->globalScaleFactor;
3742 }
3743 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003744 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003745
hongzuo liu95785e22022-09-06 02:51:35 +00003746 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003747 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003748 switch (downEventEntry->type) {
3749 case EventEntry::Type::MOTION: {
3750 logOutboundMotionDetails("down - ",
3751 static_cast<const MotionEntry&>(*downEventEntry));
3752 break;
3753 }
3754
3755 case EventEntry::Type::KEY:
3756 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003757 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003758 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003759 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003760 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003761 case EventEntry::Type::SENSOR:
3762 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003763 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003764 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003765 break;
3766 }
3767 }
3768
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003769 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003770 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003771 }
3772
hongzuo liu95785e22022-09-06 02:51:35 +00003773 // If the outbound queue was previously empty, start the dispatch cycle going.
3774 if (wasEmpty && !connection->outboundQueue.empty()) {
3775 startDispatchCycleLocked(downTime, connection);
3776 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003777}
3778
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003779std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003780 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 ALOG_ASSERT(pointerIds.value != 0);
3782
3783 uint32_t splitPointerIndexMap[MAX_POINTERS];
3784 PointerProperties splitPointerProperties[MAX_POINTERS];
3785 PointerCoords splitPointerCoords[MAX_POINTERS];
3786
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003787 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 uint32_t splitPointerCount = 0;
3789
3790 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003791 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003793 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 uint32_t pointerId = uint32_t(pointerProperties.id);
3795 if (pointerIds.hasBit(pointerId)) {
3796 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3797 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3798 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003799 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 splitPointerCount += 1;
3801 }
3802 }
3803
3804 if (splitPointerCount != pointerIds.count()) {
3805 // This is bad. We are missing some of the pointers that we expected to deliver.
3806 // Most likely this indicates that we received an ACTION_MOVE events that has
3807 // different pointer ids than we expected based on the previous ACTION_DOWN
3808 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3809 // in this way.
3810 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003811 "we expected there to be %d pointers. This probably means we received "
3812 "a broken sequence of pointer ids from the input device.",
3813 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003814 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003817 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3820 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3822 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003823 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 uint32_t pointerId = uint32_t(pointerProperties.id);
3825 if (pointerIds.hasBit(pointerId)) {
3826 if (pointerIds.count() == 1) {
3827 // The first/last pointer went down/up.
3828 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003830 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3831 ? AMOTION_EVENT_ACTION_CANCEL
3832 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 } else {
3834 // A secondary pointer went down/up.
3835 uint32_t splitPointerIndex = 0;
3836 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3837 splitPointerIndex += 1;
3838 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003839 action = maskedAction |
3840 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 }
3842 } else {
3843 // An unrelated pointer changed.
3844 action = AMOTION_EVENT_ACTION_MOVE;
3845 }
3846 }
3847
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003848 if (action == AMOTION_EVENT_ACTION_DOWN) {
3849 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3850 "Split motion event has mismatching downTime and eventTime for "
3851 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3852 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3853 }
3854
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003855 int32_t newId = mIdGenerator.nextId();
3856 if (ATRACE_ENABLED()) {
3857 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3858 ") to MotionEvent(id=0x%" PRIx32 ").",
3859 originalMotionEntry.id, newId);
3860 ATRACE_NAME(message.c_str());
3861 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003862 std::unique_ptr<MotionEntry> splitMotionEntry =
3863 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3864 originalMotionEntry.deviceId, originalMotionEntry.source,
3865 originalMotionEntry.displayId,
3866 originalMotionEntry.policyFlags, action,
3867 originalMotionEntry.actionButton,
3868 originalMotionEntry.flags, originalMotionEntry.metaState,
3869 originalMotionEntry.buttonState,
3870 originalMotionEntry.classification,
3871 originalMotionEntry.edgeFlags,
3872 originalMotionEntry.xPrecision,
3873 originalMotionEntry.yPrecision,
3874 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003875 originalMotionEntry.yCursorPosition, splitDownTime,
3876 splitPointerCount, splitPointerProperties,
3877 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003879 if (originalMotionEntry.injectionState) {
3880 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 splitMotionEntry->injectionState->refCount += 1;
3882 }
3883
3884 return splitMotionEntry;
3885}
3886
3887void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003888 if (DEBUG_INBOUND_EVENT_DETAILS) {
3889 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
Antonio Kantekf16f2832021-09-28 04:39:20 +00003892 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003894 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003896 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3897 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3898 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 } // release lock
3900
3901 if (needWake) {
3902 mLooper->wake();
3903 }
3904}
3905
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003906/**
3907 * If one of the meta shortcuts is detected, process them here:
3908 * Meta + Backspace -> generate BACK
3909 * Meta + Enter -> generate HOME
3910 * This will potentially overwrite keyCode and metaState.
3911 */
3912void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003913 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003914 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3915 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3916 if (keyCode == AKEYCODE_DEL) {
3917 newKeyCode = AKEYCODE_BACK;
3918 } else if (keyCode == AKEYCODE_ENTER) {
3919 newKeyCode = AKEYCODE_HOME;
3920 }
3921 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003922 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003923 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003924 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003925 keyCode = newKeyCode;
3926 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3927 }
3928 } else if (action == AKEY_EVENT_ACTION_UP) {
3929 // In order to maintain a consistent stream of up and down events, check to see if the key
3930 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3931 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003932 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003933 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003934 auto replacementIt = mReplacedKeys.find(replacement);
3935 if (replacementIt != mReplacedKeys.end()) {
3936 keyCode = replacementIt->second;
3937 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003938 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3939 }
3940 }
3941}
3942
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003944 if (DEBUG_INBOUND_EVENT_DETAILS) {
3945 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3946 "policyFlags=0x%x, action=0x%x, "
3947 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3948 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3949 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3950 args->downTime);
3951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 if (!validateKeyEvent(args->action)) {
3953 return;
3954 }
3955
3956 uint32_t policyFlags = args->policyFlags;
3957 int32_t flags = args->flags;
3958 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003959 // InputDispatcher tracks and generates key repeats on behalf of
3960 // whatever notifies it, so repeatCount should always be set to 0
3961 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3963 policyFlags |= POLICY_FLAG_VIRTUAL;
3964 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 if (policyFlags & POLICY_FLAG_FUNCTION) {
3967 metaState |= AMETA_FUNCTION_ON;
3968 }
3969
3970 policyFlags |= POLICY_FLAG_TRUSTED;
3971
Michael Wright78f24442014-08-06 15:55:28 -07003972 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003973 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003974
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003976 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003977 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3978 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
Michael Wright2b3c3302018-03-02 17:19:13 +00003980 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003982 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3983 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003984 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986
Antonio Kantekf16f2832021-09-28 04:39:20 +00003987 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 { // acquire lock
3989 mLock.lock();
3990
3991 if (shouldSendKeyToInputFilterLocked(args)) {
3992 mLock.unlock();
3993
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003994 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3996 return; // event was consumed by the filter
3997 }
3998
3999 mLock.lock();
4000 }
4001
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::unique_ptr<KeyEntry> newEntry =
4003 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4004 args->displayId, policyFlags, args->action, flags,
4005 keyCode, args->scanCode, metaState, repeatCount,
4006 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004008 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 mLock.unlock();
4010 } // release lock
4011
4012 if (needWake) {
4013 mLooper->wake();
4014 }
4015}
4016
4017bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4018 return mInputFilterEnabled;
4019}
4020
4021void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004022 if (DEBUG_INBOUND_EVENT_DETAILS) {
4023 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4024 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004025 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004026 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4027 "yCursorPosition=%f, downTime=%" PRId64,
4028 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004029 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4030 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4031 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4032 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004033 for (uint32_t i = 0; i < args->pointerCount; i++) {
4034 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4035 "x=%f, y=%f, pressure=%f, size=%f, "
4036 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4037 "orientation=%f",
4038 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4039 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4040 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4041 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4042 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4043 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4044 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4045 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4046 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4047 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004050 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4051 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 return;
4053 }
4054
4055 uint32_t policyFlags = args->policyFlags;
4056 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004057
4058 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004059 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004060 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4061 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064
Antonio Kantekf16f2832021-09-28 04:39:20 +00004065 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 { // acquire lock
4067 mLock.lock();
4068
4069 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004070 ui::Transform displayTransform;
4071 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4072 displayTransform = it->second.transform;
4073 }
4074
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 mLock.unlock();
4076
4077 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004078 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4079 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004080 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004081 displayTransform, args->xPrecision, args->yPrecision,
4082 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004083 args->downTime, args->eventTime, args->pointerCount,
4084 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
4086 policyFlags |= POLICY_FLAG_FILTERED;
4087 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4088 return; // event was consumed by the filter
4089 }
4090
4091 mLock.lock();
4092 }
4093
4094 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004095 std::unique_ptr<MotionEntry> newEntry =
4096 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4097 args->source, args->displayId, policyFlags,
4098 args->action, args->actionButton, args->flags,
4099 args->metaState, args->buttonState,
4100 args->classification, args->edgeFlags,
4101 args->xPrecision, args->yPrecision,
4102 args->xCursorPosition, args->yCursorPosition,
4103 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004104 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004106 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4107 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4108 !mInputFilterEnabled) {
4109 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4110 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4111 }
4112
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004113 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 mLock.unlock();
4115 } // release lock
4116
4117 if (needWake) {
4118 mLooper->wake();
4119 }
4120}
4121
Chris Yef59a2f42020-10-16 12:55:26 -07004122void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004123 if (DEBUG_INBOUND_EVENT_DETAILS) {
4124 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4125 " sensorType=%s",
4126 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004127 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004128 }
Chris Yef59a2f42020-10-16 12:55:26 -07004129
Antonio Kantekf16f2832021-09-28 04:39:20 +00004130 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004131 { // acquire lock
4132 mLock.lock();
4133
4134 // Just enqueue a new sensor event.
4135 std::unique_ptr<SensorEntry> newEntry =
4136 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4137 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4138 args->sensorType, args->accuracy,
4139 args->accuracyChanged, args->values);
4140
4141 needWake = enqueueInboundEventLocked(std::move(newEntry));
4142 mLock.unlock();
4143 } // release lock
4144
4145 if (needWake) {
4146 mLooper->wake();
4147 }
4148}
4149
Chris Yefb552902021-02-03 17:18:37 -08004150void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004151 if (DEBUG_INBOUND_EVENT_DETAILS) {
4152 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4153 args->deviceId, args->isOn);
4154 }
Chris Yefb552902021-02-03 17:18:37 -08004155 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4156}
4157
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004159 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160}
4161
4162void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004163 if (DEBUG_INBOUND_EVENT_DETAILS) {
4164 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4165 "switchMask=0x%08x",
4166 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
4169 uint32_t policyFlags = args->policyFlags;
4170 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172}
4173
4174void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004175 if (DEBUG_INBOUND_EVENT_DETAILS) {
4176 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4177 args->deviceId);
4178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Antonio Kantekf16f2832021-09-28 04:39:20 +00004180 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004182 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004184 std::unique_ptr<DeviceResetEntry> newEntry =
4185 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4186 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 } // release lock
4188
4189 if (needWake) {
4190 mLooper->wake();
4191 }
4192}
4193
Prabir Pradhan7e186182020-11-10 13:56:45 -08004194void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004195 if (DEBUG_INBOUND_EVENT_DETAILS) {
4196 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004197 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004198 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004199
Antonio Kantekf16f2832021-09-28 04:39:20 +00004200 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004201 { // acquire lock
4202 std::scoped_lock _l(mLock);
4203 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004204 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004205 needWake = enqueueInboundEventLocked(std::move(entry));
4206 } // release lock
4207
4208 if (needWake) {
4209 mLooper->wake();
4210 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004211}
4212
Prabir Pradhan5735a322022-04-11 17:23:34 +00004213InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4214 std::optional<int32_t> targetUid,
4215 InputEventInjectionSync syncMode,
4216 std::chrono::milliseconds timeout,
4217 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004218 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004219 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4220 "policyFlags=0x%08x",
4221 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4222 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004223 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004224 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225
Prabir Pradhan5735a322022-04-11 17:23:34 +00004226 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004228 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004229 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4230 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4231 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4232 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4233 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004235 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004236 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 }
4238
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004239 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004242 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4243 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004245 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004248 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004249 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4250 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4251 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004252 int32_t keyCode = incomingKey.getKeyCode();
4253 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004254 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004256 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004257 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004258 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4259 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4260 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4263 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004264 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265
4266 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4267 android::base::Timer t;
4268 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4269 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4270 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4271 std::to_string(t.duration().count()).c_str());
4272 }
4273 }
4274
4275 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276 std::unique_ptr<KeyEntry> injectedEntry =
4277 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004278 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 incomingKey.getDisplayId(), policyFlags, action,
4280 flags, keyCode, incomingKey.getScanCode(), metaState,
4281 incomingKey.getRepeatCount(),
4282 incomingKey.getDownTime());
4283 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 }
4286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004288 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004289 const int32_t action = motionEvent.getAction();
4290 const bool isPointerEvent =
4291 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4292 // If a pointer event has no displayId specified, inject it to the default display.
4293 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4294 ? ADISPLAY_ID_DEFAULT
4295 : event->getDisplayId();
4296 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004297 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004298 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004299 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004302 }
4303
4304 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004305 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 android::base::Timer t;
4307 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4308 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4309 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4310 std::to_string(t.duration().count()).c_str());
4311 }
4312 }
4313
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004314 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4315 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4316 }
4317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004319 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4320 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004321 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004322 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4323 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004324 displayId, policyFlags, action, actionButton,
4325 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004326 motionEvent.getButtonState(),
4327 motionEvent.getClassification(),
4328 motionEvent.getEdgeFlags(),
4329 motionEvent.getXPrecision(),
4330 motionEvent.getYPrecision(),
4331 motionEvent.getRawXCursorPosition(),
4332 motionEvent.getRawYCursorPosition(),
4333 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004334 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004335 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004336 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004337 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004338 sampleEventTimes += 1;
4339 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004340 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004341 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4342 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004343 displayId, policyFlags, action, actionButton,
4344 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004345 motionEvent.getButtonState(),
4346 motionEvent.getClassification(),
4347 motionEvent.getEdgeFlags(),
4348 motionEvent.getXPrecision(),
4349 motionEvent.getYPrecision(),
4350 motionEvent.getRawXCursorPosition(),
4351 motionEvent.getRawYCursorPosition(),
4352 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004353 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004354 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004355 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4356 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004357 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004358 }
4359 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004362 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004363 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 }
4366
Prabir Pradhan5735a322022-04-11 17:23:34 +00004367 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 injectionState->injectionIsAsync = true;
4370 }
4371
4372 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004373 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
4375 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004376 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004377 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004378 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 }
4380
4381 mLock.unlock();
4382
4383 if (needWake) {
4384 mLooper->wake();
4385 }
4386
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004389 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 if (syncMode == InputEventInjectionSync::NONE) {
4392 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 } else {
4394 for (;;) {
4395 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 break;
4398 }
4399
4400 nsecs_t remainingTimeout = endTime - now();
4401 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004402 if (DEBUG_INJECTION) {
4403 ALOGD("injectInputEvent - Timed out waiting for injection result "
4404 "to become available.");
4405 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 break;
4408 }
4409
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004410 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 }
4412
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004413 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4414 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004416 if (DEBUG_INJECTION) {
4417 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4418 injectionState->pendingForegroundDispatches);
4419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 nsecs_t remainingTimeout = endTime - now();
4421 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004422 if (DEBUG_INJECTION) {
4423 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4424 "dispatches to finish.");
4425 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004426 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 break;
4428 }
4429
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004430 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 }
4432 }
4433 }
4434
4435 injectionState->release();
4436 } // release lock
4437
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004438 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004439 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441
4442 return injectionResult;
4443}
4444
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004445std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004446 std::array<uint8_t, 32> calculatedHmac;
4447 std::unique_ptr<VerifiedInputEvent> result;
4448 switch (event.getType()) {
4449 case AINPUT_EVENT_TYPE_KEY: {
4450 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4451 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4452 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004453 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004454 break;
4455 }
4456 case AINPUT_EVENT_TYPE_MOTION: {
4457 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4458 VerifiedMotionEvent verifiedMotionEvent =
4459 verifiedMotionEventFromMotionEvent(motionEvent);
4460 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004461 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004462 break;
4463 }
4464 default: {
4465 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4466 return nullptr;
4467 }
4468 }
4469 if (calculatedHmac == INVALID_HMAC) {
4470 return nullptr;
4471 }
4472 if (calculatedHmac != event.getHmac()) {
4473 return nullptr;
4474 }
4475 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004476}
4477
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004478void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004479 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004480 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004482 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004483 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 // Log the outcome since the injector did not wait for the injection result.
4488 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004489 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004490 ALOGV("Asynchronous input event injection succeeded.");
4491 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004492 case InputEventInjectionResult::TARGET_MISMATCH:
4493 ALOGV("Asynchronous input event injection target mismatch.");
4494 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 ALOGW("Asynchronous input event injection failed.");
4497 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004498 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004499 ALOGW("Asynchronous input event injection timed out.");
4500 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 case InputEventInjectionResult::PENDING:
4502 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4503 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 }
4505 }
4506
4507 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004508 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 }
4510}
4511
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004512void InputDispatcher::transformMotionEntryForInjectionLocked(
4513 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004514 // Input injection works in the logical display coordinate space, but the input pipeline works
4515 // display space, so we need to transform the injected events accordingly.
4516 const auto it = mDisplayInfos.find(entry.displayId);
4517 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004518 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004519
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004520 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4521 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4522 const vec2 cursor =
4523 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4524 {entry.xCursorPosition, entry.yCursorPosition});
4525 entry.xCursorPosition = cursor.x;
4526 entry.yCursorPosition = cursor.y;
4527 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004528 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004529 entry.pointerCoords[i] =
4530 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4531 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004532 }
4533}
4534
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004535void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4536 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 if (injectionState) {
4538 injectionState->pendingForegroundDispatches += 1;
4539 }
4540}
4541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004542void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4543 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 if (injectionState) {
4545 injectionState->pendingForegroundDispatches -= 1;
4546
4547 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004548 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 }
4550 }
4551}
4552
chaviw98318de2021-05-19 16:45:23 -05004553const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004554 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004555 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004556 auto it = mWindowHandlesByDisplay.find(displayId);
4557 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004558}
4559
chaviw98318de2021-05-19 16:45:23 -05004560sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004561 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004562 if (windowHandleToken == nullptr) {
4563 return nullptr;
4564 }
4565
Arthur Hungb92218b2018-08-14 12:00:21 +08004566 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004567 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4568 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004569 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004570 return windowHandle;
4571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 }
4573 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004574 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575}
4576
chaviw98318de2021-05-19 16:45:23 -05004577sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4578 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004579 if (windowHandleToken == nullptr) {
4580 return nullptr;
4581 }
4582
chaviw98318de2021-05-19 16:45:23 -05004583 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004584 if (windowHandle->getToken() == windowHandleToken) {
4585 return windowHandle;
4586 }
4587 }
4588 return nullptr;
4589}
4590
chaviw98318de2021-05-19 16:45:23 -05004591sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4592 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004593 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004594 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4595 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004596 if (handle->getId() == windowHandle->getId() &&
4597 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004598 if (windowHandle->getInfo()->displayId != it.first) {
4599 ALOGE("Found window %s in display %" PRId32
4600 ", but it should belong to display %" PRId32,
4601 windowHandle->getName().c_str(), it.first,
4602 windowHandle->getInfo()->displayId);
4603 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004604 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 }
4607 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004608 return nullptr;
4609}
4610
chaviw98318de2021-05-19 16:45:23 -05004611sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004612 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4613 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614}
4615
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004616bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4617 const MotionEntry& motionEntry) const {
4618 const WindowInfo& info = *window->getInfo();
4619
4620 // Skip spy window targets that are not valid for targeted injection.
4621 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004622 return false;
4623 }
4624
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004625 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4626 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4627 return false;
4628 }
4629
4630 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4631 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4632 window->getName().c_str());
4633 return false;
4634 }
4635
4636 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004637 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004638 ALOGW("Not sending touch to %s because there's no corresponding connection",
4639 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004640 return false;
4641 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004642
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004643 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004644 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004645 return false;
4646 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004647
4648 // Drop events that can't be trusted due to occlusion
4649 const auto [x, y] = resolveTouchedPosition(motionEntry);
4650 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4651 if (!isTouchTrustedLocked(occlusionInfo)) {
4652 if (DEBUG_TOUCH_OCCLUSION) {
4653 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4654 for (const auto& log : occlusionInfo.debugInfo) {
4655 ALOGD("%s", log.c_str());
4656 }
4657 }
4658 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4659 occlusionInfo.obscuringUid);
4660 return false;
4661 }
4662
4663 // Drop touch events if requested by input feature
4664 if (shouldDropInput(motionEntry, window)) {
4665 return false;
4666 }
4667
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004668 return true;
4669}
4670
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004671std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4672 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004673 auto connectionIt = mConnectionsByToken.find(token);
4674 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004675 return nullptr;
4676 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004677 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004678}
4679
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004680void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004681 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4682 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004683 // Remove all handles on a display if there are no windows left.
4684 mWindowHandlesByDisplay.erase(displayId);
4685 return;
4686 }
4687
4688 // Since we compare the pointer of input window handles across window updates, we need
4689 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004690 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4691 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4692 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004693 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004694 }
4695
chaviw98318de2021-05-19 16:45:23 -05004696 std::vector<sp<WindowInfoHandle>> newHandles;
4697 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004698 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004699 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004700 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004701 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004702 const bool canReceiveInput =
4703 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4704 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004705 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004706 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004707 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004708 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004709 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004710 }
4711
4712 if (info->displayId != displayId) {
4713 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4714 handle->getName().c_str(), displayId, info->displayId);
4715 continue;
4716 }
4717
Robert Carredd13602020-04-13 17:24:34 -07004718 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4719 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004720 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004721 oldHandle->updateFrom(handle);
4722 newHandles.push_back(oldHandle);
4723 } else {
4724 newHandles.push_back(handle);
4725 }
4726 }
4727
4728 // Insert or replace
4729 mWindowHandlesByDisplay[displayId] = newHandles;
4730}
4731
Arthur Hung72d8dc32020-03-28 00:48:39 +00004732void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004733 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004734 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004735 { // acquire lock
4736 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004737 for (const auto& [displayId, handles] : handlesPerDisplay) {
4738 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004739 }
4740 }
4741 // Wake up poll loop since it may need to make new input dispatching choices.
4742 mLooper->wake();
4743}
4744
Arthur Hungb92218b2018-08-14 12:00:21 +08004745/**
4746 * Called from InputManagerService, update window handle list by displayId that can receive input.
4747 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4748 * If set an empty list, remove all handles from the specific display.
4749 * For focused handle, check if need to change and send a cancel event to previous one.
4750 * For removed handle, check if need to send a cancel event if already in touch.
4751 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004752void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004753 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004754 if (DEBUG_FOCUS) {
4755 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004756 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004757 windowList += iwh->getName() + " ";
4758 }
4759 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761
Prabir Pradhand65552b2021-10-07 11:23:50 -07004762 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004763 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004764 const WindowInfo& info = *window->getInfo();
4765
4766 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004767 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004768 if (noInputWindow && window->getToken() != nullptr) {
4769 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4770 window->getName().c_str());
4771 window->releaseChannel();
4772 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004773
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004774 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004775 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4776 !info.inputConfig.test(
4777 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004778 "%s has feature SPY, but is not a trusted overlay.",
4779 window->getName().c_str());
4780
Prabir Pradhand65552b2021-10-07 11:23:50 -07004781 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004782 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4783 !info.inputConfig.test(
4784 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004785 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4786 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004787 }
4788
Arthur Hung72d8dc32020-03-28 00:48:39 +00004789 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004790 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004792 // Save the old windows' orientation by ID before it gets updated.
4793 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004794 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004795 oldWindowOrientations.emplace(handle->getId(),
4796 handle->getInfo()->transform.getOrientation());
4797 }
4798
chaviw98318de2021-05-19 16:45:23 -05004799 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004800
chaviw98318de2021-05-19 16:45:23 -05004801 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004802 if (mLastHoverWindowHandle &&
4803 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4804 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004805 mLastHoverWindowHandle = nullptr;
4806 }
4807
Vishnu Nairc519ff72021-01-21 08:23:08 -08004808 std::optional<FocusResolver::FocusChanges> changes =
4809 mFocusResolver.setInputWindows(displayId, windowHandles);
4810 if (changes) {
4811 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004814 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4815 mTouchStatesByDisplay.find(displayId);
4816 if (stateIt != mTouchStatesByDisplay.end()) {
4817 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004818 for (size_t i = 0; i < state.windows.size();) {
4819 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004820 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004821 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004822 ALOGD("Touched window was removed: %s in display %" PRId32,
4823 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004824 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004825 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004826 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4827 if (touchedInputChannel != nullptr) {
4828 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4829 "touched window was removed");
4830 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004831 // Since we are about to drop the touch, cancel the events for the wallpaper as
4832 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004833 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004834 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4835 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004836 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4837 if (wallpaper != nullptr) {
4838 sp<Connection> wallpaperConnection =
4839 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004840 if (wallpaperConnection != nullptr) {
4841 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4842 options);
4843 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004844 }
4845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004847 state.windows.erase(state.windows.begin() + i);
4848 } else {
4849 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 }
4851 }
arthurhungb89ccb02020-12-30 16:19:01 +08004852
arthurhung6d4bed92021-03-17 11:59:33 +08004853 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004854 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004855 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004856 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004857 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004858 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4859 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004860 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004861 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004862 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004863
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004864 // Determine if the orientation of any of the input windows have changed, and cancel all
4865 // pointer events if necessary.
4866 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4867 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4868 if (newWindowHandle != nullptr &&
4869 newWindowHandle->getInfo()->transform.getOrientation() !=
4870 oldWindowOrientations[oldWindowHandle->getId()]) {
4871 std::shared_ptr<InputChannel> inputChannel =
4872 getInputChannelLocked(newWindowHandle->getToken());
4873 if (inputChannel != nullptr) {
4874 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4875 "touched window's orientation changed");
4876 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004877 }
4878 }
4879 }
4880
Arthur Hung72d8dc32020-03-28 00:48:39 +00004881 // Release information for windows that are no longer present.
4882 // This ensures that unused input channels are released promptly.
4883 // Otherwise, they might stick around until the window handle is destroyed
4884 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004885 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004886 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004887 if (DEBUG_FOCUS) {
4888 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004889 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004890 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004891 }
chaviw291d88a2019-02-14 10:33:58 -08004892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
4895void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004896 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004897 if (DEBUG_FOCUS) {
4898 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4899 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4900 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004901 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004902 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004903 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 } // release lock
4905
4906 // Wake up poll loop since it may need to make new input dispatching choices.
4907 mLooper->wake();
4908}
4909
Vishnu Nair599f1412021-06-21 10:39:58 -07004910void InputDispatcher::setFocusedApplicationLocked(
4911 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4912 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4913 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4914
4915 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4916 return; // This application is already focused. No need to wake up or change anything.
4917 }
4918
4919 // Set the new application handle.
4920 if (inputApplicationHandle != nullptr) {
4921 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4922 } else {
4923 mFocusedApplicationHandlesByDisplay.erase(displayId);
4924 }
4925
4926 // No matter what the old focused application was, stop waiting on it because it is
4927 // no longer focused.
4928 resetNoFocusedWindowTimeoutLocked();
4929}
4930
Tiger Huang721e26f2018-07-24 22:26:19 +08004931/**
4932 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4933 * the display not specified.
4934 *
4935 * We track any unreleased events for each window. If a window loses the ability to receive the
4936 * released event, we will send a cancel event to it. So when the focused display is changed, we
4937 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4938 * display. The display-specified events won't be affected.
4939 */
4940void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004941 if (DEBUG_FOCUS) {
4942 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4943 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004944 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004945 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004946
4947 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004948 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004949 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004950 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004951 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004952 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004953 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004954 CancelationOptions
4955 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4956 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004957 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004958 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4959 }
4960 }
4961 mFocusedDisplayId = displayId;
4962
Chris Ye3c2d6f52020-08-09 10:39:48 -07004963 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004964 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004965 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004966
Vishnu Nairad321cd2020-08-20 16:40:21 -07004967 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004968 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004969 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004970 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004971 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004972 }
4973 }
4974 }
4975
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004976 if (DEBUG_FOCUS) {
4977 logDispatchStateLocked();
4978 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004979 } // release lock
4980
4981 // Wake up poll loop since it may need to make new input dispatching choices.
4982 mLooper->wake();
4983}
4984
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004986 if (DEBUG_FOCUS) {
4987 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989
4990 bool changed;
4991 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004992 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993
4994 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4995 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004996 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 }
4998
4999 if (mDispatchEnabled && !enabled) {
5000 resetAndDropEverythingLocked("dispatcher is being disabled");
5001 }
5002
5003 mDispatchEnabled = enabled;
5004 mDispatchFrozen = frozen;
5005 changed = true;
5006 } else {
5007 changed = false;
5008 }
5009
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005010 if (DEBUG_FOCUS) {
5011 logDispatchStateLocked();
5012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 } // release lock
5014
5015 if (changed) {
5016 // Wake up poll loop since it may need to make new input dispatching choices.
5017 mLooper->wake();
5018 }
5019}
5020
5021void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005022 if (DEBUG_FOCUS) {
5023 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025
5026 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005027 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028
5029 if (mInputFilterEnabled == enabled) {
5030 return;
5031 }
5032
5033 mInputFilterEnabled = enabled;
5034 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5035 } // release lock
5036
5037 // Wake up poll loop since there might be work to do to drop everything.
5038 mLooper->wake();
5039}
5040
Antonio Kanteka042c022022-07-06 16:51:07 -07005041bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5042 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005043 bool needWake = false;
5044 {
5045 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005046 ALOGD_IF(DEBUG_TOUCH_MODE,
5047 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5048 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5049 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5050 mTouchModePerDisplay.count(displayId) == 0
5051 ? "not set"
5052 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5053
Antonio Kantek15beb512022-06-13 22:35:41 +00005054 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5055 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005056 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005057 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005058 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005059 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5060 !recentWindowsAreOwnedByLocked(pid, uid)) {
5061 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5062 "window nor none of the previously interacted window",
5063 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005064 return false;
5065 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005066 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005067 mTouchModePerDisplay[displayId] = inTouchMode;
5068 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5069 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005070 needWake = enqueueInboundEventLocked(std::move(entry));
5071 } // release lock
5072
5073 if (needWake) {
5074 mLooper->wake();
5075 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005076 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005077}
5078
Antonio Kantek48710e42022-03-24 14:19:30 -07005079bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5080 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5081 if (focusedToken == nullptr) {
5082 return false;
5083 }
5084 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5085 return isWindowOwnedBy(windowHandle, pid, uid);
5086}
5087
5088bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5089 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5090 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5091 const sp<WindowInfoHandle> windowHandle =
5092 getWindowHandleLocked(connectionToken);
5093 return isWindowOwnedBy(windowHandle, pid, uid);
5094 }) != mInteractionConnectionTokens.end();
5095}
5096
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005097void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5098 if (opacity < 0 || opacity > 1) {
5099 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5100 return;
5101 }
5102
5103 std::scoped_lock lock(mLock);
5104 mMaximumObscuringOpacityForTouch = opacity;
5105}
5106
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005107std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5108InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005109 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5110 for (TouchedWindow& w : state.windows) {
5111 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005112 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005113 }
5114 }
5115 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005116 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005117}
5118
arthurhungb89ccb02020-12-30 16:19:01 +08005119bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5120 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005121 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005122 if (DEBUG_FOCUS) {
5123 ALOGD("Trivial transfer to same window.");
5124 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005125 return true;
5126 }
5127
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005129 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130
Arthur Hungabbb9d82021-09-01 14:52:30 +00005131 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005132 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005133 if (state == nullptr || touchedWindow == nullptr) {
5134 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 return false;
5136 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005137
Arthur Hungabbb9d82021-09-01 14:52:30 +00005138 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5139 if (toWindowHandle == nullptr) {
5140 ALOGW("Cannot transfer focus because to window not found.");
5141 return false;
5142 }
5143
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005144 if (DEBUG_FOCUS) {
5145 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005146 touchedWindow->windowHandle->getName().c_str(),
5147 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148 }
5149
Arthur Hungabbb9d82021-09-01 14:52:30 +00005150 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005151 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005152 BitSet32 pointerIds = touchedWindow->pointerIds;
5153 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154
Arthur Hungabbb9d82021-09-01 14:52:30 +00005155 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005156 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005157 ftl::Flags<InputTarget::Flags> newTargetFlags =
5158 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005159 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005160 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005161 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005162 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163
Arthur Hungabbb9d82021-09-01 14:52:30 +00005164 // Store the dragging window.
5165 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005166 if (pointerIds.count() != 1) {
5167 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5168 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005169 return false;
5170 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005171 // Track the pointer id for drag window and generate the drag state.
5172 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005173 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 }
5175
Arthur Hungabbb9d82021-09-01 14:52:30 +00005176 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005177 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5178 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005179 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005180 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005181 CancelationOptions
5182 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5183 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005185 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 }
5187
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005188 if (DEBUG_FOCUS) {
5189 logDispatchStateLocked();
5190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 } // release lock
5192
5193 // Wake up poll loop since it may need to make new input dispatching choices.
5194 mLooper->wake();
5195 return true;
5196}
5197
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005198/**
5199 * Get the touched foreground window on the given display.
5200 * Return null if there are no windows touched on that display, or if more than one foreground
5201 * window is being touched.
5202 */
5203sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5204 auto stateIt = mTouchStatesByDisplay.find(displayId);
5205 if (stateIt == mTouchStatesByDisplay.end()) {
5206 ALOGI("No touch state on display %" PRId32, displayId);
5207 return nullptr;
5208 }
5209
5210 const TouchState& state = stateIt->second;
5211 sp<WindowInfoHandle> touchedForegroundWindow;
5212 // If multiple foreground windows are touched, return nullptr
5213 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005214 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005215 if (touchedForegroundWindow != nullptr) {
5216 ALOGI("Two or more foreground windows: %s and %s",
5217 touchedForegroundWindow->getName().c_str(),
5218 window.windowHandle->getName().c_str());
5219 return nullptr;
5220 }
5221 touchedForegroundWindow = window.windowHandle;
5222 }
5223 }
5224 return touchedForegroundWindow;
5225}
5226
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005227// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005228bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005229 sp<IBinder> fromToken;
5230 { // acquire lock
5231 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005232 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005233 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005234 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5235 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005236 return false;
5237 }
5238
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005239 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5240 if (from == nullptr) {
5241 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5242 return false;
5243 }
5244
5245 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005246 } // release lock
5247
5248 return transferTouchFocus(fromToken, destChannelToken);
5249}
5250
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005252 if (DEBUG_FOCUS) {
5253 ALOGD("Resetting and dropping all events (%s).", reason);
5254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255
5256 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5257 synthesizeCancelationEventsForAllConnectionsLocked(options);
5258
5259 resetKeyRepeatLocked();
5260 releasePendingEventLocked();
5261 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005262 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005264 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005265 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005267 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268}
5269
5270void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005271 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 dumpDispatchStateLocked(dump);
5273
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005274 std::istringstream stream(dump);
5275 std::string line;
5276
5277 while (std::getline(stream, line, '\n')) {
5278 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 }
5280}
5281
Prabir Pradhan99987712020-11-10 18:43:05 -08005282std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5283 std::string dump;
5284
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005285 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5286 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005287
5288 std::string windowName = "None";
5289 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005290 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005291 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5292 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5293 : "token has capture without window";
5294 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005295 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005296
5297 return dump;
5298}
5299
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005300void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005301 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5302 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5303 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005304 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305
Tiger Huang721e26f2018-07-24 22:26:19 +08005306 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5307 dump += StringPrintf(INDENT "FocusedApplications:\n");
5308 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5309 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005310 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005311 const std::chrono::duration timeout =
5312 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005313 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005314 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005315 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005318 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005320
Vishnu Nairc519ff72021-01-21 08:23:08 -08005321 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005322 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005324 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005325 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005326 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005327 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5328 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 }
5330 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005331 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 }
5333
arthurhung6d4bed92021-03-17 11:59:33 +08005334 if (mDragState) {
5335 dump += StringPrintf(INDENT "DragState:\n");
5336 mDragState->dump(dump, INDENT2);
5337 }
5338
Arthur Hungb92218b2018-08-14 12:00:21 +08005339 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005340 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5341 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5342 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5343 const auto& displayInfo = it->second;
5344 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5345 displayInfo.logicalHeight);
5346 displayInfo.transform.dump(dump, "transform", INDENT4);
5347 } else {
5348 dump += INDENT2 "No DisplayInfo found!\n";
5349 }
5350
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005351 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005352 dump += INDENT2 "Windows:\n";
5353 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005354 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5355 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005357 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005358 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005359 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005360 "applicationInfo.name=%s, "
5361 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005362 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005363 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005364 windowInfo->displayId,
5365 windowInfo->inputConfig.string().c_str(),
5366 windowInfo->alpha, windowInfo->frameLeft,
5367 windowInfo->frameTop, windowInfo->frameRight,
5368 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005369 windowInfo->applicationInfo.name.c_str(),
5370 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005371 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005372 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005373 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005374 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005375 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005376 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005377 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005378 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005379 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005380 }
5381 } else {
5382 dump += INDENT2 "Windows: <none>\n";
5383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 }
5385 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005386 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 }
5388
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005389 if (!mGlobalMonitorsByDisplay.empty()) {
5390 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5391 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005392 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005395 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
5397
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005398 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399
5400 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005401 if (!mRecentQueue.empty()) {
5402 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005403 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005404 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005405 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005406 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005409 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 }
5411
5412 // Dump event currently being dispatched.
5413 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005414 dump += INDENT "PendingEvent:\n";
5415 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005416 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005417 dump += StringPrintf(", age=%" PRId64 "ms\n",
5418 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005420 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 }
5422
5423 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005424 if (!mInboundQueue.empty()) {
5425 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005426 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005427 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005428 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005429 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
5431 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005432 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 }
5434
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005435 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005437 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5438 const KeyReplacement& replacement = pair.first;
5439 int32_t newKeyCode = pair.second;
5440 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005441 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005442 }
5443 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005444 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005445 }
5446
Prabir Pradhancef936d2021-07-21 16:17:52 +00005447 if (!mCommandQueue.empty()) {
5448 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5449 } else {
5450 dump += INDENT "CommandQueue: <empty>\n";
5451 }
5452
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005453 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005454 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005455 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005456 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005457 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005458 connection->inputChannel->getFd().get(),
5459 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005460 connection->getWindowName().c_str(),
5461 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005462 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005464 if (!connection->outboundQueue.empty()) {
5465 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5466 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005467 dump += dumpQueue(connection->outboundQueue, currentTime);
5468
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005470 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005473 if (!connection->waitQueue.empty()) {
5474 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5475 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005476 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005478 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 }
5480 }
5481 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005482 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 }
5484
5485 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005486 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5487 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005489 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 }
5491
Antonio Kantek15beb512022-06-13 22:35:41 +00005492 if (!mTouchModePerDisplay.empty()) {
5493 dump += INDENT "TouchModePerDisplay:\n";
5494 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5495 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5496 std::to_string(touchMode).c_str());
5497 }
5498 } else {
5499 dump += INDENT "TouchModePerDisplay: <none>\n";
5500 }
5501
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005502 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005503 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5504 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5505 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005506 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005507 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508}
5509
Michael Wright3dd60e22019-03-27 22:06:44 +00005510void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5511 const size_t numMonitors = monitors.size();
5512 for (size_t i = 0; i < numMonitors; i++) {
5513 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005514 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005515 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5516 dump += "\n";
5517 }
5518}
5519
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005520class LooperEventCallback : public LooperCallback {
5521public:
5522 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5523 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5524
5525private:
5526 std::function<int(int events)> mCallback;
5527};
5528
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005529Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005530 if (DEBUG_CHANNEL_CREATION) {
5531 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005534 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005535 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005536 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005537
5538 if (result) {
5539 return base::Error(result) << "Failed to open input channel pair with name " << name;
5540 }
5541
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005543 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005544 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005545 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005546 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005547 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005549 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5550 ALOGE("Created a new connection, but the token %p is already known", token.get());
5551 }
5552 mConnectionsByToken.emplace(token, connection);
5553
5554 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5555 this, std::placeholders::_1, token);
5556
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005557 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5558 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 } // release lock
5560
5561 // Wake the looper because some connections have changed.
5562 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005563 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564}
5565
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005566Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005567 const std::string& name,
5568 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005569 std::shared_ptr<InputChannel> serverChannel;
5570 std::unique_ptr<InputChannel> clientChannel;
5571 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5572 if (result) {
5573 return base::Error(result) << "Failed to open input channel pair with name " << name;
5574 }
5575
Michael Wright3dd60e22019-03-27 22:06:44 +00005576 { // acquire lock
5577 std::scoped_lock _l(mLock);
5578
5579 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005580 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5581 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005582 }
5583
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005584 sp<Connection> connection =
5585 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005586 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005587 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005588
5589 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5590 ALOGE("Created a new connection, but the token %p is already known", token.get());
5591 }
5592 mConnectionsByToken.emplace(token, connection);
5593 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5594 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005595
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005596 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005597
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005598 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5599 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005600 }
Garfield Tan15601662020-09-22 15:32:38 -07005601
Michael Wright3dd60e22019-03-27 22:06:44 +00005602 // Wake the looper because some connections have changed.
5603 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005604 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005605}
5606
Garfield Tan15601662020-09-22 15:32:38 -07005607status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005609 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610
Garfield Tan15601662020-09-22 15:32:38 -07005611 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 if (status) {
5613 return status;
5614 }
5615 } // release lock
5616
5617 // Wake the poll loop because removing the connection may have changed the current
5618 // synchronization state.
5619 mLooper->wake();
5620 return OK;
5621}
5622
Garfield Tan15601662020-09-22 15:32:38 -07005623status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5624 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005625 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005626 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005627 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 return BAD_VALUE;
5629 }
5630
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005631 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005632
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005634 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 }
5636
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005637 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638
5639 nsecs_t currentTime = now();
5640 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5641
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005642 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 return OK;
5644}
5645
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005646void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005647 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5648 auto& [displayId, monitors] = *it;
5649 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5650 return monitor.inputChannel->getConnectionToken() == connectionToken;
5651 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005652
Michael Wright3dd60e22019-03-27 22:06:44 +00005653 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005654 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005655 } else {
5656 ++it;
5657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658 }
5659}
5660
Michael Wright3dd60e22019-03-27 22:06:44 +00005661status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005662 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005663 return pilferPointersLocked(token);
5664}
Michael Wright3dd60e22019-03-27 22:06:44 +00005665
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005666status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005667 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5668 if (!requestingChannel) {
5669 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5670 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005671 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005672
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005673 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005674 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005675 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5676 " Ignoring.");
5677 return BAD_VALUE;
5678 }
5679
5680 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005681 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005682 // Send cancel events to all the input channels we're stealing from.
5683 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5684 "input channel stole pointer stream");
5685 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005686 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005687 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005688 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005689 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005690 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005691 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005692 if (channel != nullptr && channel->getConnectionToken() != token) {
5693 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5694 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5695 canceledWindows += channel->getName();
5696 }
5697 }
5698 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5699 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5700 canceledWindows.c_str());
5701
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005702 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005703 // This only blocks relevant pointers to be sent to other windows
5704 window.isPilferingPointers = true;
5705
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005706 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005707 return OK;
5708}
5709
Prabir Pradhan99987712020-11-10 18:43:05 -08005710void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5711 { // acquire lock
5712 std::scoped_lock _l(mLock);
5713 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005714 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005715 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5716 windowHandle != nullptr ? windowHandle->getName().c_str()
5717 : "token without window");
5718 }
5719
Vishnu Nairc519ff72021-01-21 08:23:08 -08005720 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005721 if (focusedToken != windowToken) {
5722 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5723 enabled ? "enable" : "disable");
5724 return;
5725 }
5726
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005727 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005728 ALOGW("Ignoring request to %s Pointer Capture: "
5729 "window has %s requested pointer capture.",
5730 enabled ? "enable" : "disable", enabled ? "already" : "not");
5731 return;
5732 }
5733
Christine Franksb768bb42021-11-29 12:11:31 -08005734 if (enabled) {
5735 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5736 mIneligibleDisplaysForPointerCapture.end(),
5737 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5738 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5739 return;
5740 }
5741 }
5742
Prabir Pradhan99987712020-11-10 18:43:05 -08005743 setPointerCaptureLocked(enabled);
5744 } // release lock
5745
5746 // Wake the thread to process command entries.
5747 mLooper->wake();
5748}
5749
Christine Franksb768bb42021-11-29 12:11:31 -08005750void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5751 { // acquire lock
5752 std::scoped_lock _l(mLock);
5753 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5754 if (!isEligible) {
5755 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5756 }
5757 } // release lock
5758}
5759
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005760std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5761 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005762 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005763 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005764 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005765 }
5766 }
5767 }
5768 return std::nullopt;
5769}
5770
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005771sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005772 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005773 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005774 }
5775
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005776 for (const auto& [token, connection] : mConnectionsByToken) {
5777 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005778 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 }
5780 }
Robert Carr4e670e52018-08-15 13:26:12 -07005781
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005782 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783}
5784
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005785std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5786 sp<Connection> connection = getConnectionLocked(connectionToken);
5787 if (connection == nullptr) {
5788 return "<nullptr>";
5789 }
5790 return connection->getInputChannelName();
5791}
5792
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005793void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005794 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005795 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005796}
5797
Prabir Pradhancef936d2021-07-21 16:17:52 +00005798void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5799 const sp<Connection>& connection, uint32_t seq,
5800 bool handled, nsecs_t consumeTime) {
5801 // Handle post-event policy actions.
5802 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5803 if (dispatchEntryIt == connection->waitQueue.end()) {
5804 return;
5805 }
5806 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5807 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5808 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5809 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5810 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5811 }
5812 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5813 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5814 connection->inputChannel->getConnectionToken(),
5815 dispatchEntry->deliveryTime, consumeTime, finishTime);
5816 }
5817
5818 bool restartEvent;
5819 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5820 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5821 restartEvent =
5822 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5823 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5824 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5825 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5826 handled);
5827 } else {
5828 restartEvent = false;
5829 }
5830
5831 // Dequeue the event and start the next cycle.
5832 // Because the lock might have been released, it is possible that the
5833 // contents of the wait queue to have been drained, so we need to double-check
5834 // a few things.
5835 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5836 if (dispatchEntryIt != connection->waitQueue.end()) {
5837 dispatchEntry = *dispatchEntryIt;
5838 connection->waitQueue.erase(dispatchEntryIt);
5839 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5840 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5841 if (!connection->responsive) {
5842 connection->responsive = isConnectionResponsive(*connection);
5843 if (connection->responsive) {
5844 // The connection was unresponsive, and now it's responsive.
5845 processConnectionResponsiveLocked(*connection);
5846 }
5847 }
5848 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005849 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005850 connection->outboundQueue.push_front(dispatchEntry);
5851 traceOutboundQueueLength(*connection);
5852 } else {
5853 releaseDispatchEntry(dispatchEntry);
5854 }
5855 }
5856
5857 // Start the next dispatch cycle for this connection.
5858 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005859}
5860
Prabir Pradhancef936d2021-07-21 16:17:52 +00005861void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5862 const sp<IBinder>& newToken) {
5863 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5864 scoped_unlock unlock(mLock);
5865 mPolicy->notifyFocusChanged(oldToken, newToken);
5866 };
5867 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868}
5869
Prabir Pradhancef936d2021-07-21 16:17:52 +00005870void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5871 auto command = [this, token, x, y]() REQUIRES(mLock) {
5872 scoped_unlock unlock(mLock);
5873 mPolicy->notifyDropWindow(token, x, y);
5874 };
5875 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005876}
5877
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005878void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5879 if (connection == nullptr) {
5880 LOG_ALWAYS_FATAL("Caller must check for nullness");
5881 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005882 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5883 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005884 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005885 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005886 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005887 return;
5888 }
5889 /**
5890 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5891 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5892 * has changed. This could cause newer entries to time out before the already dispatched
5893 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5894 * processes the events linearly. So providing information about the oldest entry seems to be
5895 * most useful.
5896 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005897 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5899 std::string reason =
5900 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005901 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005902 ns2ms(currentWait),
5903 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005904 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005905 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005906
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005907 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5908
5909 // Stop waking up for events on this connection, it is already unresponsive
5910 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005911}
5912
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005913void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5914 std::string reason =
5915 StringPrintf("%s does not have a focused window", application->getName().c_str());
5916 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005917
Prabir Pradhancef936d2021-07-21 16:17:52 +00005918 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5919 scoped_unlock unlock(mLock);
5920 mPolicy->notifyNoFocusedWindowAnr(application);
5921 };
5922 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005923}
5924
chaviw98318de2021-05-19 16:45:23 -05005925void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005926 const std::string& reason) {
5927 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5928 updateLastAnrStateLocked(windowLabel, reason);
5929}
5930
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005931void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5932 const std::string& reason) {
5933 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005934 updateLastAnrStateLocked(windowLabel, reason);
5935}
5936
5937void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5938 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005940 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 struct tm tm;
5942 localtime_r(&t, &tm);
5943 char timestr[64];
5944 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005945 mLastAnrState.clear();
5946 mLastAnrState += INDENT "ANR:\n";
5947 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005948 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5949 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005950 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005951}
5952
Prabir Pradhancef936d2021-07-21 16:17:52 +00005953void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5954 KeyEntry& entry) {
5955 const KeyEvent event = createKeyEvent(entry);
5956 nsecs_t delay = 0;
5957 { // release lock
5958 scoped_unlock unlock(mLock);
5959 android::base::Timer t;
5960 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5961 entry.policyFlags);
5962 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5963 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5964 std::to_string(t.duration().count()).c_str());
5965 }
5966 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967
5968 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005969 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005970 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005971 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005973 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5974 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976}
5977
Prabir Pradhancef936d2021-07-21 16:17:52 +00005978void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005979 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005980 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005981 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005982 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005983 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005984 };
5985 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005986}
5987
Prabir Pradhanedd96402022-02-15 01:46:16 -08005988void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5989 std::optional<int32_t> pid) {
5990 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005991 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005992 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005993 };
5994 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005995}
5996
5997/**
5998 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5999 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6000 * command entry to the command queue.
6001 */
6002void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6003 std::string reason) {
6004 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006005 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006006 if (connection.monitor) {
6007 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6008 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006009 pid = findMonitorPidByTokenLocked(connectionToken);
6010 } else {
6011 // The connection is a window
6012 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6013 reason.c_str());
6014 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6015 if (handle != nullptr) {
6016 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006017 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006018 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006019 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006020}
6021
6022/**
6023 * Tell the policy that a connection has become responsive so that it can stop ANR.
6024 */
6025void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6026 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006027 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006029 pid = findMonitorPidByTokenLocked(connectionToken);
6030 } else {
6031 // The connection is a window
6032 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6033 if (handle != nullptr) {
6034 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006035 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006036 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006037 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006038}
6039
Prabir Pradhancef936d2021-07-21 16:17:52 +00006040bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006041 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006042 KeyEntry& keyEntry, bool handled) {
6043 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006044 if (!handled) {
6045 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006046 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006047 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006048 return false;
6049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006051 // Get the fallback key state.
6052 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006053 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006055 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056 connection->inputState.removeFallbackKey(originalKeyCode);
6057 }
6058
6059 if (handled || !dispatchEntry->hasForegroundTarget()) {
6060 // If the application handles the original key for which we previously
6061 // generated a fallback or if the window is not a foreground window,
6062 // then cancel the associated fallback key, if any.
6063 if (fallbackKeyCode != -1) {
6064 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006065 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6066 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6067 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6068 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6069 keyEntry.policyFlags);
6070 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006071 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006072 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073
6074 mLock.unlock();
6075
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006076 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006077 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006078
6079 mLock.lock();
6080
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006081 // Cancel the fallback key.
6082 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006084 "application handled the original non-fallback key "
6085 "or is no longer a foreground target, "
6086 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 options.keyCode = fallbackKeyCode;
6088 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 connection->inputState.removeFallbackKey(originalKeyCode);
6091 }
6092 } else {
6093 // If the application did not handle a non-fallback key, first check
6094 // that we are in a good state to perform unhandled key event processing
6095 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006096 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006097 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006098 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6099 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6100 "since this is not an initial down. "
6101 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6102 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6103 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006104 return false;
6105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006106
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006107 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006108 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6109 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6110 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6111 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6112 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006113 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006114
6115 mLock.unlock();
6116
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006117 bool fallback =
6118 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006119 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120
6121 mLock.lock();
6122
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006123 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006124 connection->inputState.removeFallbackKey(originalKeyCode);
6125 return false;
6126 }
6127
6128 // Latch the fallback keycode for this key on an initial down.
6129 // The fallback keycode cannot change at any other point in the lifecycle.
6130 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006132 fallbackKeyCode = event.getKeyCode();
6133 } else {
6134 fallbackKeyCode = AKEYCODE_UNKNOWN;
6135 }
6136 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6137 }
6138
6139 ALOG_ASSERT(fallbackKeyCode != -1);
6140
6141 // Cancel the fallback key if the policy decides not to send it anymore.
6142 // We will continue to dispatch the key to the policy but we will no
6143 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006144 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6145 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006146 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6147 if (fallback) {
6148 ALOGD("Unhandled key event: Policy requested to send key %d"
6149 "as a fallback for %d, but on the DOWN it had requested "
6150 "to send %d instead. Fallback canceled.",
6151 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6152 } else {
6153 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6154 "but on the DOWN it had requested to send %d. "
6155 "Fallback canceled.",
6156 originalKeyCode, fallbackKeyCode);
6157 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006158 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006159
6160 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6161 "canceling fallback, policy no longer desires it");
6162 options.keyCode = fallbackKeyCode;
6163 synthesizeCancelationEventsForConnectionLocked(connection, options);
6164
6165 fallback = false;
6166 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006167 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006168 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006169 }
6170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006172 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6173 {
6174 std::string msg;
6175 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6176 connection->inputState.getFallbackKeys();
6177 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6178 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6179 }
6180 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6181 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006183 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006184
6185 if (fallback) {
6186 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006187 keyEntry.eventTime = event.getEventTime();
6188 keyEntry.deviceId = event.getDeviceId();
6189 keyEntry.source = event.getSource();
6190 keyEntry.displayId = event.getDisplayId();
6191 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6192 keyEntry.keyCode = fallbackKeyCode;
6193 keyEntry.scanCode = event.getScanCode();
6194 keyEntry.metaState = event.getMetaState();
6195 keyEntry.repeatCount = event.getRepeatCount();
6196 keyEntry.downTime = event.getDownTime();
6197 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006198
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006199 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6200 ALOGD("Unhandled key event: Dispatching fallback key. "
6201 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6202 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6203 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006204 return true; // restart the event
6205 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006206 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6207 ALOGD("Unhandled key event: No fallback key.");
6208 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006209
6210 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006211 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006212 }
6213 }
6214 return false;
6215}
6216
Prabir Pradhancef936d2021-07-21 16:17:52 +00006217bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006218 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006219 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 return false;
6221}
6222
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223void InputDispatcher::traceInboundQueueLengthLocked() {
6224 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006225 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 }
6227}
6228
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006229void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 if (ATRACE_ENABLED()) {
6231 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006232 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6233 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 }
6235}
6236
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006237void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 if (ATRACE_ENABLED()) {
6239 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006240 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6241 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006242 }
6243}
6244
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006245void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006246 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006247
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006248 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249 dumpDispatchStateLocked(dump);
6250
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006251 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006252 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006253 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254 }
6255}
6256
6257void InputDispatcher::monitor() {
6258 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006259 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006261 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262}
6263
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006264/**
6265 * Wake up the dispatcher and wait until it processes all events and commands.
6266 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6267 * this method can be safely called from any thread, as long as you've ensured that
6268 * the work you are interested in completing has already been queued.
6269 */
6270bool InputDispatcher::waitForIdle() {
6271 /**
6272 * Timeout should represent the longest possible time that a device might spend processing
6273 * events and commands.
6274 */
6275 constexpr std::chrono::duration TIMEOUT = 100ms;
6276 std::unique_lock lock(mLock);
6277 mLooper->wake();
6278 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6279 return result == std::cv_status::no_timeout;
6280}
6281
Vishnu Naire798b472020-07-23 13:52:21 -07006282/**
6283 * Sets focus to the window identified by the token. This must be called
6284 * after updating any input window handles.
6285 *
6286 * Params:
6287 * request.token - input channel token used to identify the window that should gain focus.
6288 * request.focusedToken - the token that the caller expects currently to be focused. If the
6289 * specified token does not match the currently focused window, this request will be dropped.
6290 * If the specified focused token matches the currently focused window, the call will succeed.
6291 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6292 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6293 * when requesting the focus change. This determines which request gets
6294 * precedence if there is a focus change request from another source such as pointer down.
6295 */
Vishnu Nair958da932020-08-21 17:12:37 -07006296void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6297 { // acquire lock
6298 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006299 std::optional<FocusResolver::FocusChanges> changes =
6300 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6301 if (changes) {
6302 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006303 }
6304 } // release lock
6305 // Wake up poll loop since it may need to make new input dispatching choices.
6306 mLooper->wake();
6307}
6308
Vishnu Nairc519ff72021-01-21 08:23:08 -08006309void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6310 if (changes.oldFocus) {
6311 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006312 if (focusedInputChannel) {
6313 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6314 "focus left window");
6315 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006316 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006317 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006318 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006319 if (changes.newFocus) {
6320 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006321 }
6322
Prabir Pradhan99987712020-11-10 18:43:05 -08006323 // If a window has pointer capture, then it must have focus. We need to ensure that this
6324 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6325 // If the window loses focus before it loses pointer capture, then the window can be in a state
6326 // where it has pointer capture but not focus, violating the contract. Therefore we must
6327 // dispatch the pointer capture event before the focus event. Since focus events are added to
6328 // the front of the queue (above), we add the pointer capture event to the front of the queue
6329 // after the focus events are added. This ensures the pointer capture event ends up at the
6330 // front.
6331 disablePointerCaptureForcedLocked();
6332
Vishnu Nairc519ff72021-01-21 08:23:08 -08006333 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006334 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006335 }
6336}
Vishnu Nair958da932020-08-21 17:12:37 -07006337
Prabir Pradhan99987712020-11-10 18:43:05 -08006338void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006339 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006340 return;
6341 }
6342
6343 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6344
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006345 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006346 setPointerCaptureLocked(false);
6347 }
6348
6349 if (!mWindowTokenWithPointerCapture) {
6350 // No need to send capture changes because no window has capture.
6351 return;
6352 }
6353
6354 if (mPendingEvent != nullptr) {
6355 // Move the pending event to the front of the queue. This will give the chance
6356 // for the pending event to be dropped if it is a captured event.
6357 mInboundQueue.push_front(mPendingEvent);
6358 mPendingEvent = nullptr;
6359 }
6360
6361 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006362 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006363 mInboundQueue.push_front(std::move(entry));
6364}
6365
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006366void InputDispatcher::setPointerCaptureLocked(bool enable) {
6367 mCurrentPointerCaptureRequest.enable = enable;
6368 mCurrentPointerCaptureRequest.seq++;
6369 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006370 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006371 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006372 };
6373 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006374}
6375
Vishnu Nair599f1412021-06-21 10:39:58 -07006376void InputDispatcher::displayRemoved(int32_t displayId) {
6377 { // acquire lock
6378 std::scoped_lock _l(mLock);
6379 // Set an empty list to remove all handles from the specific display.
6380 setInputWindowsLocked(/* window handles */ {}, displayId);
6381 setFocusedApplicationLocked(displayId, nullptr);
6382 // Call focus resolver to clean up stale requests. This must be called after input windows
6383 // have been removed for the removed display.
6384 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006385 // Reset pointer capture eligibility, regardless of previous state.
6386 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006387 // Remove the associated touch mode state.
6388 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006389 } // release lock
6390
6391 // Wake up poll loop since it may need to make new input dispatching choices.
6392 mLooper->wake();
6393}
6394
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006395void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6396 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006397 // The listener sends the windows as a flattened array. Separate the windows by display for
6398 // more convenient parsing.
6399 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006400 for (const auto& info : windowInfos) {
6401 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006402 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006403 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006404
6405 { // acquire lock
6406 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006407
6408 // Ensure that we have an entry created for all existing displays so that if a displayId has
6409 // no windows, we can tell that the windows were removed from the display.
6410 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6411 handlesPerDisplay[displayId];
6412 }
6413
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006414 mDisplayInfos.clear();
6415 for (const auto& displayInfo : displayInfos) {
6416 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6417 }
6418
6419 for (const auto& [displayId, handles] : handlesPerDisplay) {
6420 setInputWindowsLocked(handles, displayId);
6421 }
6422 }
6423 // Wake up poll loop since it may need to make new input dispatching choices.
6424 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006425}
6426
Vishnu Nair062a8672021-09-03 16:07:44 -07006427bool InputDispatcher::shouldDropInput(
6428 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006429 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6430 (windowHandle->getInfo()->inputConfig.test(
6431 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006432 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006433 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6434 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006435 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006436 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006437 windowHandle->getInfo()->displayId);
6438 return true;
6439 }
6440 return false;
6441}
6442
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006443void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6444 const std::vector<gui::WindowInfo>& windowInfos,
6445 const std::vector<DisplayInfo>& displayInfos) {
6446 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6447}
6448
Arthur Hungdfd528e2021-12-08 13:23:04 +00006449void InputDispatcher::cancelCurrentTouch() {
6450 {
6451 std::scoped_lock _l(mLock);
6452 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6453 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6454 "cancel current touch");
6455 synthesizeCancelationEventsForAllConnectionsLocked(options);
6456
6457 mTouchStatesByDisplay.clear();
6458 mLastHoverWindowHandle.clear();
6459 }
6460 // Wake up poll loop since there might be work to do.
6461 mLooper->wake();
6462}
6463
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006464void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6465 std::scoped_lock _l(mLock);
6466 mMonitorDispatchingTimeout = timeout;
6467}
6468
Garfield Tane84e6f92019-08-29 17:28:41 -07006469} // namespace android::inputdispatcher