blob: 87a4ff4f35c400397a7b43877c6e9122be6cb1ac [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) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000484 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700485}
486
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800487// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000488// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
489// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
490// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800491// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000492bool canReceiveForegroundTouches(const WindowInfo& info) {
493 // A non-touchable window can still receive touch events (e.g. in the case of
494 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
495 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
496}
497
Antonio Kantek48710e42022-03-24 14:19:30 -0700498bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
499 if (windowHandle == nullptr) {
500 return false;
501 }
502 const WindowInfo* windowInfo = windowHandle->getInfo();
503 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
504 return true;
505 }
506 return false;
507}
508
Prabir Pradhan5735a322022-04-11 17:23:34 +0000509// Checks targeted injection using the window's owner's uid.
510// Returns an empty string if an entry can be sent to the given window, or an error message if the
511// entry is a targeted injection whose uid target doesn't match the window owner.
512std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
513 const EventEntry& entry) {
514 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
515 // The event was not injected, or the injected event does not target a window.
516 return {};
517 }
518 const int32_t uid = *entry.injectionState->targetUid;
519 if (window == nullptr) {
520 return StringPrintf("No valid window target for injection into uid %d.", uid);
521 }
522 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
523 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
524 "owned by uid %d.",
525 uid, window->getName().c_str(), window->getInfo()->ownerUid);
526 }
527 return {};
528}
529
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700530Point resolveTouchedPosition(const MotionEntry& entry) {
531 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
532 // Always dispatch mouse events to cursor position.
533 if (isFromMouse) {
534 return Point(static_cast<int32_t>(entry.xCursorPosition),
535 static_cast<int32_t>(entry.yCursorPosition));
536 }
537
538 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
539 return Point(static_cast<int32_t>(
540 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
541 static_cast<int32_t>(
542 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
543}
544
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700545std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
546 if (eventEntry.type == EventEntry::Type::KEY) {
547 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
548 return keyEntry.downTime;
549 } else if (eventEntry.type == EventEntry::Type::MOTION) {
550 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
551 return motionEntry.downTime;
552 }
553 return std::nullopt;
554}
555
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000556} // namespace
557
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558// --- InputDispatcher ---
559
Garfield Tan00f511d2019-06-12 16:55:40 -0700560InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800561 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
562
563InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
564 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700565 : mPolicy(policy),
566 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700567 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800568 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700569 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700570 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700571 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800572 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700573 mDispatchEnabled(false),
574 mDispatchFrozen(false),
575 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100576 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000577 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800578 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800579 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000580 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000581 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700582 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800583 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700585 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700586#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700587 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700588#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700589 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 policy->getDispatcherConfiguration(&mConfig);
591}
592
593InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000594 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595
Prabir Pradhancef936d2021-07-21 16:17:52 +0000596 resetKeyRepeatLocked();
597 releasePendingEventLocked();
598 drainInboundQueueLocked();
599 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000601 while (!mConnectionsByToken.empty()) {
602 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000603 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
604 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 }
606}
607
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700608status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700609 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700610 return ALREADY_EXISTS;
611 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700612 mThread = std::make_unique<InputThread>(
613 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
614 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700615}
616
617status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700618 if (mThread && mThread->isCallingThread()) {
619 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700620 return INVALID_OPERATION;
621 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700622 mThread.reset();
623 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700624}
625
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700627 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800629 std::scoped_lock _l(mLock);
630 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631
632 // Run a dispatch loop if there are no pending commands.
633 // The dispatch loop might enqueue commands to run afterwards.
634 if (!haveCommandsLocked()) {
635 dispatchOnceInnerLocked(&nextWakeupTime);
636 }
637
638 // Run all pending commands if there are any.
639 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000640 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700641 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800643
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700644 // If we are still waiting for ack on some events,
645 // we might have to wake up earlier to check if an app is anr'ing.
646 const nsecs_t nextAnrCheck = processAnrsLocked();
647 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
648
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800649 // We are about to enter an infinitely long sleep, because we have no commands or
650 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700651 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800652 mDispatcherEnteredIdle.notify_all();
653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 } // release lock
655
656 // Wait for callback or timeout or wake. (make sure we round up, not down)
657 nsecs_t currentTime = now();
658 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
659 mLooper->pollOnce(timeoutMillis);
660}
661
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700662/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500663 * Raise ANR if there is no focused window.
664 * Before the ANR is raised, do a final state check:
665 * 1. The currently focused application must be the same one we are waiting for.
666 * 2. Ensure we still don't have a focused window.
667 */
668void InputDispatcher::processNoFocusedWindowAnrLocked() {
669 // Check if the application that we are waiting for is still focused.
670 std::shared_ptr<InputApplicationHandle> focusedApplication =
671 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
672 if (focusedApplication == nullptr ||
673 focusedApplication->getApplicationToken() !=
674 mAwaitedFocusedApplication->getApplicationToken()) {
675 // Unexpected because we should have reset the ANR timer when focused application changed
676 ALOGE("Waited for a focused window, but focused application has already changed to %s",
677 focusedApplication->getName().c_str());
678 return; // The focused application has changed.
679 }
680
chaviw98318de2021-05-19 16:45:23 -0500681 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500682 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
683 if (focusedWindowHandle != nullptr) {
684 return; // We now have a focused window. No need for ANR.
685 }
686 onAnrLocked(mAwaitedFocusedApplication);
687}
688
689/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700690 * Check if any of the connections' wait queues have events that are too old.
691 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
692 * Return the time at which we should wake up next.
693 */
694nsecs_t InputDispatcher::processAnrsLocked() {
695 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700696 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700697 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
698 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
699 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500700 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700701 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500702 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700703 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500705 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700706 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
707 }
708 }
709
710 // Check if any connection ANRs are due
711 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
712 if (currentTime < nextAnrCheck) { // most likely scenario
713 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
714 }
715
716 // If we reached here, we have an unresponsive connection.
717 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
718 if (connection == nullptr) {
719 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
720 return nextAnrCheck;
721 }
722 connection->responsive = false;
723 // Stop waking up for this unresponsive connection
724 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000725 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700726 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700727}
728
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800729std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
730 const sp<Connection>& connection) {
731 if (connection->monitor) {
732 return mMonitorDispatchingTimeout;
733 }
734 const sp<WindowInfoHandle> window =
735 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500737 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700738 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500739 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700740}
741
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
743 nsecs_t currentTime = now();
744
Jeff Browndc5992e2014-04-11 01:27:26 -0700745 // Reset the key repeat timer whenever normal dispatch is suspended while the
746 // device is in a non-interactive state. This is to ensure that we abort a key
747 // repeat if the device is just coming out of sleep.
748 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 resetKeyRepeatLocked();
750 }
751
752 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
753 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100754 if (DEBUG_FOCUS) {
755 ALOGD("Dispatch frozen. Waiting some more.");
756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 return;
758 }
759
760 // Optimize latency of app switches.
761 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
762 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
763 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
764 if (mAppSwitchDueTime < *nextWakeupTime) {
765 *nextWakeupTime = mAppSwitchDueTime;
766 }
767
768 // Ready to start a new event.
769 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700770 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700771 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 if (isAppSwitchDue) {
773 // The inbound queue is empty so the app switch key we were waiting
774 // for will never arrive. Stop waiting for it.
775 resetPendingAppSwitchLocked(false);
776 isAppSwitchDue = false;
777 }
778
779 // Synthesize a key repeat if appropriate.
780 if (mKeyRepeatState.lastKeyEntry) {
781 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
782 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
783 } else {
784 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
785 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
786 }
787 }
788 }
789
790 // Nothing to do if there is no pending event.
791 if (!mPendingEvent) {
792 return;
793 }
794 } else {
795 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700796 mPendingEvent = mInboundQueue.front();
797 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 traceInboundQueueLengthLocked();
799 }
800
801 // Poke user activity for this event.
802 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700803 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 }
806
807 // Now we have an event to dispatch.
808 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700809 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700813 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700815 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700819 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 }
821
822 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700823 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700824 const ConfigurationChangedEntry& typedEntry =
825 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700827 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 break;
829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700831 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700832 const DeviceResetEntry& typedEntry =
833 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700834 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700835 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700836 break;
837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100839 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700840 std::shared_ptr<FocusEntry> typedEntry =
841 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100842 dispatchFocusLocked(currentTime, typedEntry);
843 done = true;
844 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
845 break;
846 }
847
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700848 case EventEntry::Type::TOUCH_MODE_CHANGED: {
849 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
850 dispatchTouchModeChangeLocked(currentTime, typedEntry);
851 done = true;
852 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
853 break;
854 }
855
Prabir Pradhan99987712020-11-10 18:43:05 -0800856 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
857 const auto typedEntry =
858 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
859 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
860 done = true;
861 break;
862 }
863
arthurhungb89ccb02020-12-30 16:19:01 +0800864 case EventEntry::Type::DRAG: {
865 std::shared_ptr<DragEntry> typedEntry =
866 std::static_pointer_cast<DragEntry>(mPendingEvent);
867 dispatchDragLocked(currentTime, typedEntry);
868 done = true;
869 break;
870 }
871
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700872 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700875 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 resetPendingAppSwitchLocked(true);
877 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700878 } else if (dropReason == DropReason::NOT_DROPPED) {
879 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 }
881 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700882 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
886 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700888 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 break;
890 }
891
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700892 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700893 std::shared_ptr<MotionEntry> motionEntry =
894 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
896 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700898 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700901 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
902 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700904 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
Chris Yef59a2f42020-10-16 12:55:26 -0700907
908 case EventEntry::Type::SENSOR: {
909 std::shared_ptr<SensorEntry> sensorEntry =
910 std::static_pointer_cast<SensorEntry>(mPendingEvent);
911 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
912 dropReason = DropReason::APP_SWITCH;
913 }
914 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
915 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
916 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
917 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
918 dropReason = DropReason::STALE;
919 }
920 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
921 done = true;
922 break;
923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
925
926 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700927 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700928 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 }
Michael Wright3a981722015-06-10 15:26:13 +0100930 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931
932 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700933 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 }
935}
936
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800937bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
938 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
939}
940
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700941/**
942 * Return true if the events preceding this incoming motion event should be dropped
943 * Return false otherwise (the default behaviour)
944 */
945bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700947 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948
949 // Optimize case where the current application is unresponsive and the user
950 // decides to touch a window in a different application.
951 // If the application takes too long to catch up then we drop all events preceding
952 // the touch into the other window.
953 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700954 const int32_t displayId = motionEntry.displayId;
955 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700956 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700957
chaviw98318de2021-05-19 16:45:23 -0500958 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700959 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700960 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700961 touchedWindowHandle->getApplicationToken() !=
962 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700963 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700964 ALOGI("Pruning input queue because user touched a different application while waiting "
965 "for %s",
966 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700967 return true;
968 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700969
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800970 // Alternatively, maybe there's a spy window that could handle this event.
971 const std::vector<sp<WindowInfoHandle>> touchedSpies =
972 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
973 for (const auto& windowHandle : touchedSpies) {
974 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000975 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800976 // This spy window could take more input. Drop all events preceding this
977 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700978 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800979 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700980 mAwaitedFocusedApplication->getName().c_str());
981 return true;
982 }
983 }
984 }
985
986 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
987 // yet been processed by some connections, the dispatcher will wait for these motion
988 // events to be processed before dispatching the key event. This is because these motion events
989 // may cause a new window to be launched, which the user might expect to receive focus.
990 // To prevent waiting forever for such events, just send the key to the currently focused window
991 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
992 ALOGD("Received a new pointer down event, stop waiting for events to process and "
993 "just send the pending key event to the focused window.");
994 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700995 }
996 return false;
997}
998
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001000 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001001 mInboundQueue.push_back(std::move(newEntry));
1002 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 traceInboundQueueLengthLocked();
1004
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001005 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001006 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001007 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1008 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 // Optimize app switch latency.
1010 // If the application takes too long to catch up then we drop all events preceding
1011 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001012 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001014 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001016 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001018 if (DEBUG_APP_SWITCH) {
1019 ALOGD("App switch is pending!");
1020 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001021 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 mAppSwitchSawKeyDown = false;
1023 needWake = true;
1024 }
1025 }
1026 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001027
1028 // If a new up event comes in, and the pending event with same key code has been asked
1029 // to try again later because of the policy. We have to reset the intercept key wake up
1030 // time for it may have been handled in the policy and could be dropped.
1031 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1032 mPendingEvent->type == EventEntry::Type::KEY) {
1033 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1034 if (pendingKey.keyCode == keyEntry.keyCode &&
1035 pendingKey.interceptKeyResult ==
1036 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1037 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1038 pendingKey.interceptKeyWakeupTime = 0;
1039 needWake = true;
1040 }
1041 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042 break;
1043 }
1044
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001045 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001046 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1047 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001048 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1049 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001050 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001054 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001055 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1056 break;
1057 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001058 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001059 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001060 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001061 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001062 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1063 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001064 // nothing to do
1065 break;
1066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068
1069 return needWake;
1070}
1071
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001072void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001073 // Do not store sensor event in recent queue to avoid flooding the queue.
1074 if (entry->type != EventEntry::Type::SENSOR) {
1075 mRecentQueue.push_back(entry);
1076 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001077 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001078 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080}
1081
chaviw98318de2021-05-19 16:45:23 -05001082sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1083 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001084 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001085 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001086 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001087 if (addOutsideTargets && touchState == nullptr) {
1088 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001091 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001092 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001093 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001094 continue;
1095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001097 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001098 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001099 return windowHandle;
1100 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001101
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001102 if (addOutsideTargets &&
1103 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001104 touchState->addOrUpdateWindow(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001105 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 }
1107 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001108 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109}
1110
Prabir Pradhand65552b2021-10-07 11:23:50 -07001111std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1112 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001113 // Traverse windows from front to back and gather the touched spy windows.
1114 std::vector<sp<WindowInfoHandle>> spyWindows;
1115 const auto& windowHandles = getWindowHandlesLocked(displayId);
1116 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1117 const WindowInfo& info = *windowHandle->getInfo();
1118
Prabir Pradhand65552b2021-10-07 11:23:50 -07001119 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001120 continue;
1121 }
1122 if (!info.isSpy()) {
1123 // The first touched non-spy window was found, so return the spy windows touched so far.
1124 return spyWindows;
1125 }
1126 spyWindows.push_back(windowHandle);
1127 }
1128 return spyWindows;
1129}
1130
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001131void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 const char* reason;
1133 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001134 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001135 if (DEBUG_INBOUND_EVENT_DETAILS) {
1136 ALOGD("Dropped event because policy consumed it.");
1137 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 reason = "inbound event was dropped because the policy consumed it";
1139 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001140 case DropReason::DISABLED:
1141 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 ALOGI("Dropped event because input dispatch is disabled.");
1143 }
1144 reason = "inbound event was dropped because input dispatch is disabled";
1145 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 ALOGI("Dropped event because of pending overdue app switch.");
1148 reason = "inbound event was dropped because of pending overdue app switch";
1149 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001150 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001151 ALOGI("Dropped event because the current application is not responding and the user "
1152 "has started interacting with a different application.");
1153 reason = "inbound event was dropped because the current application is not responding "
1154 "and the user has started interacting with a different application";
1155 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 ALOGI("Dropped event because it is stale.");
1158 reason = "inbound event was dropped because it is stale";
1159 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001160 case DropReason::NO_POINTER_CAPTURE:
1161 ALOGI("Dropped event because there is no window with Pointer Capture.");
1162 reason = "inbound event was dropped because there is no window with Pointer Capture";
1163 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001164 case DropReason::NOT_DROPPED: {
1165 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001170 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001171 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1173 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001176 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001177 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1178 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1180 synthesizeCancelationEventsForAllConnectionsLocked(options);
1181 } else {
1182 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1183 synthesizeCancelationEventsForAllConnectionsLocked(options);
1184 }
1185 break;
1186 }
Chris Yef59a2f42020-10-16 12:55:26 -07001187 case EventEntry::Type::SENSOR: {
1188 break;
1189 }
arthurhungb89ccb02020-12-30 16:19:01 +08001190 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1191 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001192 break;
1193 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001194 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001195 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001196 case EventEntry::Type::CONFIGURATION_CHANGED:
1197 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001198 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001199 break;
1200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
1202}
1203
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001204static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001205 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1206 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207}
1208
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001209bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1210 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1211 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1212 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213}
1214
1215bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001216 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217}
1218
1219void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001220 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001222 if (DEBUG_APP_SWITCH) {
1223 if (handled) {
1224 ALOGD("App switch has arrived.");
1225 } else {
1226 ALOGD("App switch was abandoned.");
1227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229}
1230
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001232 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
Prabir Pradhancef936d2021-07-21 16:17:52 +00001235bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001236 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 return false;
1238 }
1239
1240 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001241 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001242 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001243 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1244 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001245 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 return true;
1247}
1248
Prabir Pradhancef936d2021-07-21 16:17:52 +00001249void InputDispatcher::postCommandLocked(Command&& command) {
1250 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251}
1252
1253void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001254 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001256 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 releaseInboundEventLocked(entry);
1258 }
1259 traceInboundQueueLengthLocked();
1260}
1261
1262void InputDispatcher::releasePendingEventLocked() {
1263 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001265 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001271 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001272 if (DEBUG_DISPATCH_CYCLE) {
1273 ALOGD("Injected inbound event was dropped.");
1274 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001278 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 }
1280 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281}
1282
1283void InputDispatcher::resetKeyRepeatLocked() {
1284 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001285 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
1287}
1288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1290 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
Michael Wright2e732952014-09-24 13:26:59 -07001292 uint32_t policyFlags = entry->policyFlags &
1293 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 std::shared_ptr<KeyEntry> newEntry =
1296 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1297 entry->source, entry->displayId, policyFlags, entry->action,
1298 entry->flags, entry->keyCode, entry->scanCode,
1299 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 newEntry->syntheticRepeat = true;
1302 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305}
1306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001308 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001309 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1310 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312
1313 // Reset key repeating in case a keyboard device was added or removed or something.
1314 resetKeyRepeatLocked();
1315
1316 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001317 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1318 scoped_unlock unlock(mLock);
1319 mPolicy->notifyConfigurationChanged(eventTime);
1320 };
1321 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 return true;
1323}
1324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1326 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001327 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1328 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1329 entry.deviceId);
1330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331
liushenxiang42232912021-05-21 20:24:09 +08001332 // Reset key repeating in case a keyboard device was disabled or enabled.
1333 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1334 resetKeyRepeatLocked();
1335 }
1336
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001337 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 synthesizeCancelationEventsForAllConnectionsLocked(options);
1340 return true;
1341}
1342
Vishnu Nairad321cd2020-08-20 16:40:21 -07001343void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001344 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001345 if (mPendingEvent != nullptr) {
1346 // Move the pending event to the front of the queue. This will give the chance
1347 // for the pending event to get dispatched to the newly focused window
1348 mInboundQueue.push_front(mPendingEvent);
1349 mPendingEvent = nullptr;
1350 }
1351
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001352 std::unique_ptr<FocusEntry> focusEntry =
1353 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1354 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001355
1356 // This event should go to the front of the queue, but behind all other focus events
1357 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001359 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001360 [](const std::shared_ptr<EventEntry>& event) {
1361 return event->type == EventEntry::Type::FOCUS;
1362 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001363
1364 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001365 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001366}
1367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001368void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001369 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001370 if (channel == nullptr) {
1371 return; // Window has gone away
1372 }
1373 InputTarget target;
1374 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001375 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001376 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001377 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1378 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001379 std::string reason = std::string("reason=").append(entry->reason);
1380 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001381 dispatchEventLocked(currentTime, entry, {target});
1382}
1383
Prabir Pradhan99987712020-11-10 18:43:05 -08001384void InputDispatcher::dispatchPointerCaptureChangedLocked(
1385 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1386 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001387 dropReason = DropReason::NOT_DROPPED;
1388
Prabir Pradhan99987712020-11-10 18:43:05 -08001389 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001391
1392 if (entry->pointerCaptureRequest.enable) {
1393 // Enable Pointer Capture.
1394 if (haveWindowWithPointerCapture &&
1395 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001396 // This can happen if pointer capture is disabled and re-enabled before we notify the
1397 // app of the state change, so there is no need to notify the app.
1398 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1399 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001400 }
1401 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001402 // This can happen if a window requests capture and immediately releases capture.
1403 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001404 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001405 return;
1406 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001407 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1408 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1409 return;
1410 }
1411
Vishnu Nairc519ff72021-01-21 08:23:08 -08001412 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001413 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1414 mWindowTokenWithPointerCapture = token;
1415 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001416 // Disable Pointer Capture.
1417 // We do not check if the sequence number matches for requests to disable Pointer Capture
1418 // for two reasons:
1419 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1420 // to disable capture with the same sequence number: one generated by
1421 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1422 // Capture being disabled in InputReader.
1423 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1424 // actual Pointer Capture state that affects events being generated by input devices is
1425 // in InputReader.
1426 if (!haveWindowWithPointerCapture) {
1427 // Pointer capture was already forcefully disabled because of focus change.
1428 dropReason = DropReason::NOT_DROPPED;
1429 return;
1430 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001431 token = mWindowTokenWithPointerCapture;
1432 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001433 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001434 setPointerCaptureLocked(false);
1435 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001436 }
1437
1438 auto channel = getInputChannelLocked(token);
1439 if (channel == nullptr) {
1440 // Window has gone away, clean up Pointer Capture state.
1441 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001442 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001443 setPointerCaptureLocked(false);
1444 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001445 return;
1446 }
1447 InputTarget target;
1448 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001449 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001450 entry->dispatchInProgress = true;
1451 dispatchEventLocked(currentTime, entry, {target});
1452
1453 dropReason = DropReason::NOT_DROPPED;
1454}
1455
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001456void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1457 const std::shared_ptr<TouchModeEntry>& entry) {
1458 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001459 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001460 if (windowHandles.empty()) {
1461 return;
1462 }
1463 const std::vector<InputTarget> inputTargets =
1464 getInputTargetsFromWindowHandlesLocked(windowHandles);
1465 if (inputTargets.empty()) {
1466 return;
1467 }
1468 entry->dispatchInProgress = true;
1469 dispatchEventLocked(currentTime, entry, inputTargets);
1470}
1471
1472std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1473 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1474 std::vector<InputTarget> inputTargets;
1475 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001476 const sp<IBinder>& token = handle->getToken();
1477 if (token == nullptr) {
1478 continue;
1479 }
1480 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1481 if (channel == nullptr) {
1482 continue; // Window has gone away
1483 }
1484 InputTarget target;
1485 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001486 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001487 inputTargets.push_back(target);
1488 }
1489 return inputTargets;
1490}
1491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001492bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 if (!entry->dispatchInProgress) {
1496 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1497 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1498 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1499 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001500 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 // We have seen two identical key downs in a row which indicates that the device
1502 // driver is automatically generating key repeats itself. We take note of the
1503 // repeat here, but we disable our own next key repeat timer since it is clear that
1504 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001505 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1506 // Make sure we don't get key down from a different device. If a different
1507 // device Id has same key pressed down, the new device Id will replace the
1508 // current one to hold the key repeat with repeat count reset.
1509 // In the future when got a KEY_UP on the device id, drop it and do not
1510 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1512 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001513 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 } else {
1515 // Not a repeat. Save key down state in case we do see a repeat later.
1516 resetKeyRepeatLocked();
1517 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1518 }
1519 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001520 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1521 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001523 if (DEBUG_INBOUND_EVENT_DETAILS) {
1524 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1525 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001526 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 resetKeyRepeatLocked();
1528 }
1529
1530 if (entry->repeatCount == 1) {
1531 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1532 } else {
1533 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1534 }
1535
1536 entry->dispatchInProgress = true;
1537
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 }
1540
1541 // Handle case where the policy asked us to try again later last time.
1542 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1543 if (currentTime < entry->interceptKeyWakeupTime) {
1544 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1545 *nextWakeupTime = entry->interceptKeyWakeupTime;
1546 }
1547 return false; // wait until next wakeup
1548 }
1549 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1550 entry->interceptKeyWakeupTime = 0;
1551 }
1552
1553 // Give the policy a chance to intercept the key.
1554 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1555 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001556 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001557 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001558
1559 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1560 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1561 };
1562 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 return false; // wait for the command to run
1564 } else {
1565 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1566 }
1567 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001568 if (*dropReason == DropReason::NOT_DROPPED) {
1569 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571 }
1572
1573 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001574 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1577 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001578 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 return true;
1580 }
1581
1582 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001583 InputEventInjectionResult injectionResult;
1584 sp<WindowInfoHandle> focusedWindow =
1585 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1586 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001587 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 return false;
1589 }
1590
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001591 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001592 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 return true;
1594 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001595 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1596
1597 std::vector<InputTarget> inputTargets;
1598 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001599 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001600 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001602 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604
1605 // Dispatch the key.
1606 dispatchEventLocked(currentTime, entry, inputTargets);
1607 return true;
1608}
1609
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001611 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1612 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1613 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1614 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1615 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1616 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1617 entry.metaState, entry.repeatCount, entry.downTime);
1618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619}
1620
Prabir Pradhancef936d2021-07-21 16:17:52 +00001621void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1622 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001623 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001624 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1625 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1626 "source=0x%x, sensorType=%s",
1627 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001628 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001629 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001630 auto command = [this, entry]() REQUIRES(mLock) {
1631 scoped_unlock unlock(mLock);
1632
1633 if (entry->accuracyChanged) {
1634 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1635 }
1636 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1637 entry->hwTimestamp, entry->values);
1638 };
1639 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001640}
1641
1642bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001643 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1644 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001645 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001646 }
Chris Yef59a2f42020-10-16 12:55:26 -07001647 { // acquire lock
1648 std::scoped_lock _l(mLock);
1649
1650 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1651 std::shared_ptr<EventEntry> entry = *it;
1652 if (entry->type == EventEntry::Type::SENSOR) {
1653 it = mInboundQueue.erase(it);
1654 releaseInboundEventLocked(entry);
1655 }
1656 }
1657 }
1658 return true;
1659}
1660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 entry->dispatchInProgress = true;
1667
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670
1671 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001672 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001673 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001674 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1675 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 return true;
1677 }
1678
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001679 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
1681 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001682 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683
1684 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001685 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 if (isPointerEvent) {
1687 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001688
1689 if (mDragState &&
1690 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1691 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1692 pilferPointersLocked(mDragState->dragWindow->getToken());
1693 }
1694
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001695 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001696 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001697 /*byref*/ injectionResult);
1698 for (const TouchedWindow& touchedWindow : touchedWindows) {
1699 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1700 "Shouldn't be adding window if the injection didn't succeed.");
1701 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1702 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1703 inputTargets);
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 } else {
1706 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001707 sp<WindowInfoHandle> focusedWindow =
1708 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1709 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1710 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1711 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001712 InputTarget::Flags::FOREGROUND |
1713 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001714 BitSet32(0), getDownTime(*entry), inputTargets);
1715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001717 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 return false;
1719 }
1720
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001721 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001722 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001723 return true;
1724 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001725 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001726 CancelationOptions::Mode mode(isPointerEvent
1727 ? CancelationOptions::CANCEL_POINTER_EVENTS
1728 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1729 CancelationOptions options(mode, "input event injection failed");
1730 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 return true;
1732 }
1733
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001734 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736
1737 // Dispatch the motion.
1738 if (conflictingPointerActions) {
1739 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 synthesizeCancelationEventsForAllConnectionsLocked(options);
1742 }
1743 dispatchEventLocked(currentTime, entry, inputTargets);
1744 return true;
1745}
1746
chaviw98318de2021-05-19 16:45:23 -05001747void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001748 bool isExiting, const int32_t rawX,
1749 const int32_t rawY) {
1750 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001751 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001752 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1753 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001754
1755 enqueueInboundEventLocked(std::move(dragEntry));
1756}
1757
1758void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1759 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1760 if (channel == nullptr) {
1761 return; // Window has gone away
1762 }
1763 InputTarget target;
1764 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001765 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001766 entry->dispatchInProgress = true;
1767 dispatchEventLocked(currentTime, entry, {target});
1768}
1769
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001770void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001771 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1772 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1773 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001774 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001775 "metaState=0x%x, buttonState=0x%x,"
1776 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1777 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001778 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1779 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1780 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001782 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1783 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1784 "x=%f, y=%f, pressure=%f, size=%f, "
1785 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1786 "orientation=%f",
1787 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1788 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1796 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799}
1800
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001801void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1802 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001803 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001804 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001805 if (DEBUG_DISPATCH_CYCLE) {
1806 ALOGD("dispatchEventToCurrentInputTargets");
1807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001809 updateInteractionTokensLocked(*eventEntry, inputTargets);
1810
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1812
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001813 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001815 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001816 sp<Connection> connection =
1817 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001818 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001819 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001821 if (DEBUG_FOCUS) {
1822 ALOGD("Dropping event delivery to target with channel '%s' because it "
1823 "is no longer registered with the input dispatcher.",
1824 inputTarget.inputChannel->getName().c_str());
1825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827 }
1828}
1829
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001830void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1831 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1832 // If the policy decides to close the app, we will get a channel removal event via
1833 // unregisterInputChannel, and will clean up the connection that way. We are already not
1834 // sending new pointers to the connection when it blocked, but focused events will continue to
1835 // pile up.
1836 ALOGW("Canceling events for %s because it is unresponsive",
1837 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001838 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1840 "application not responding");
1841 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 }
1843}
1844
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001845void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001846 if (DEBUG_FOCUS) {
1847 ALOGD("Resetting ANR timeouts.");
1848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849
1850 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001851 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001852 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853}
1854
Tiger Huang721e26f2018-07-24 22:26:19 +08001855/**
1856 * Get the display id that the given event should go to. If this event specifies a valid display id,
1857 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1858 * Focused display is the display that the user most recently interacted with.
1859 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001860int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001861 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001862 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001863 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001864 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1865 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001866 break;
1867 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001868 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001869 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1870 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001871 break;
1872 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001873 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001874 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001875 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001876 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001877 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001878 case EventEntry::Type::SENSOR:
1879 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001880 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001881 return ADISPLAY_ID_NONE;
1882 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001883 }
1884 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1885}
1886
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1888 const char* focusedWindowName) {
1889 if (mAnrTracker.empty()) {
1890 // already processed all events that we waited for
1891 mKeyIsWaitingForEventsTimeout = std::nullopt;
1892 return false;
1893 }
1894
1895 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1896 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001897 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001898 mKeyIsWaitingForEventsTimeout = currentTime +
1899 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1900 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001901 return true;
1902 }
1903
1904 // We still have pending events, and already started the timer
1905 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1906 return true; // Still waiting
1907 }
1908
1909 // Waited too long, and some connection still hasn't processed all motions
1910 // Just send the key to the focused window
1911 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1912 focusedWindowName);
1913 mKeyIsWaitingForEventsTimeout = std::nullopt;
1914 return false;
1915}
1916
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001917sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1918 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1919 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001920 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001921 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922
Tiger Huang721e26f2018-07-24 22:26:19 +08001923 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001924 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001925 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001926 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1927
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 // If there is no currently focused window and no focused application
1929 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1931 ALOGI("Dropping %s event because there is no focused window or focused application in "
1932 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001933 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001934 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 }
1936
Vishnu Nair062a8672021-09-03 16:07:44 -07001937 // Drop key events if requested by input feature
1938 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001939 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001940 }
1941
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001942 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1943 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1944 // start interacting with another application via touch (app switch). This code can be removed
1945 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1946 // an app is expected to have a focused window.
1947 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1948 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1949 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001950 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1951 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1952 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001953 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001954 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001955 ALOGW("Waiting because no window has focus but %s may eventually add a "
1956 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001957 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001958 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001959 outInjectionResult = InputEventInjectionResult::PENDING;
1960 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001961 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1962 // Already raised ANR. Drop the event
1963 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001964 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001965 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001966 } else {
1967 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001968 outInjectionResult = InputEventInjectionResult::PENDING;
1969 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970 }
1971 }
1972
1973 // we have a valid, non-null focused window
1974 resetNoFocusedWindowTimeoutLocked();
1975
Prabir Pradhan5735a322022-04-11 17:23:34 +00001976 // Verify targeted injection.
1977 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1978 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001979 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1980 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 }
1982
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001983 if (focusedWindowHandle->getInfo()->inputConfig.test(
1984 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001985 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001986 outInjectionResult = InputEventInjectionResult::PENDING;
1987 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001988 }
1989
1990 // If the event is a key event, then we must wait for all previous events to
1991 // complete before delivering it because previous events may have the
1992 // side-effect of transferring focus to a different window and we want to
1993 // ensure that the following keys are sent to the new window.
1994 //
1995 // Suppose the user touches a button in a window then immediately presses "A".
1996 // If the button causes a pop-up window to appear then we want to ensure that
1997 // the "A" key is delivered to the new pop-up window. This is because users
1998 // often anticipate pending UI changes when typing on a keyboard.
1999 // To obtain this behavior, we must serialize key events with respect to all
2000 // prior input events.
2001 if (entry.type == EventEntry::Type::KEY) {
2002 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2003 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002004 outInjectionResult = InputEventInjectionResult::PENDING;
2005 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
2008
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002009 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2010 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011}
2012
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002013/**
2014 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2015 * that are currently unresponsive.
2016 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002017std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2018 const std::vector<Monitor>& monitors) const {
2019 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002020 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002021 [this](const Monitor& monitor) REQUIRES(mLock) {
2022 sp<Connection> connection =
2023 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 if (connection == nullptr) {
2025 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002026 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 return false;
2028 }
2029 if (!connection->responsive) {
2030 ALOGW("Unresponsive monitor %s will not get the new gesture",
2031 connection->inputChannel->getName().c_str());
2032 return false;
2033 }
2034 return true;
2035 });
2036 return responsiveMonitors;
2037}
2038
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002039/**
2040 * In general, touch should be always split between windows. Some exceptions:
2041 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2042 * from the same device, *and* the window that's receiving the current pointer does not support
2043 * split touch.
2044 * 2. Don't split mouse events
2045 */
2046bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2047 const MotionEntry& entry) const {
2048 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2049 // We should never split mouse events
2050 return false;
2051 }
2052 for (const TouchedWindow& touchedWindow : touchState.windows) {
2053 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2054 // Spy windows should not affect whether or not touch is split.
2055 continue;
2056 }
2057 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2058 continue;
2059 }
2060 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2061 // being sent there. For now, use deviceId from touch state.
2062 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2063 return false;
2064 }
2065 }
2066 return true;
2067}
2068
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002069std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002070 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2071 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002074 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 // For security reasons, we defer updating the touch state until we are sure that
2076 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002077 const int32_t displayId = entry.displayId;
2078 const int32_t action = entry.action;
2079 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080
2081 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002082 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002083 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2084 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002086 // Copy current touch state into tempTouchState.
2087 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2088 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002089 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002090 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002091 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2092 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002093 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002094 }
2095
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002096 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002097 const bool switchedDevice = (oldState != nullptr) &&
2098 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002099
2100 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2101 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2102 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2103 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2104 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002105 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 if (newGesture) {
2107 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002108 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002109 ALOGI("Dropping event because a pointer for a different device is already down "
2110 "in display %" PRId32,
2111 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002112 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002113 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002114 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002116 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002117 tempTouchState.deviceId = entry.deviceId;
2118 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002120 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002121 ALOGI("Dropping move event because a pointer for a different device is already active "
2122 "in display %" PRId32,
2123 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002124 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002125 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002126 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 }
2128
2129 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2130 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002131 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002132 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002133 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002134 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002135 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002136 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002137
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002139 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002140 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2141 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002143 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 }
2145
Prabir Pradhan5735a322022-04-11 17:23:34 +00002146 // Verify targeted injection.
2147 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2148 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002149 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002150 newTouchedWindowHandle = nullptr;
2151 goto Failed;
2152 }
2153
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002154 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002155 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002156 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2157 // New window supports splitting, but we should never split mouse events.
2158 isSplit = !isFromMouse;
2159 } else if (isSplit) {
2160 // New window does not support splitting but we have already split events.
2161 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162 newTouchedWindowHandle = nullptr;
2163 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002164 } else {
2165 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002166 // be delivered to a new window which supports split touch. Pointers from a mouse device
2167 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002168 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169 }
2170
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002171 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002172 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002173 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2174 newHoverWindowHandle = nullptr;
2175 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002176 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002177 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002178 }
2179
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002180 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002181 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002182 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002183 // Process the foreground window first so that it is the first to receive the event.
2184 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002185 }
2186
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002187 if (newTouchedWindows.empty()) {
2188 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2189 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002190 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002191 goto Failed;
2192 }
2193
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002194 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002195 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002196 continue;
2197 }
2198
2199 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002200 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002201
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002202 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2203 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002204 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002205 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002206
2207 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002208 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002209 }
2210 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002211 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002212 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002213 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002214 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002215
2216 // Update the temporary touch state.
2217 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002218 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002219
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002220 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2221 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002223
2224 // If any existing window is pilfering pointers from newly added window, remove it
2225 BitSet32 canceledPointers = BitSet32(0);
2226 for (const TouchedWindow& window : tempTouchState.windows) {
2227 if (window.isPilferingPointers) {
2228 canceledPointers |= window.pointerIds;
2229 }
2230 }
2231 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 } else {
2233 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2234
2235 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002236 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002237 ALOGD_IF(DEBUG_FOCUS,
2238 "Dropping event because the pointer is not down or we previously "
2239 "dropped the pointer down event in display %" PRId32 ": %s",
2240 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002241 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 goto Failed;
2243 }
2244
arthurhung6d4bed92021-03-17 11:59:33 +08002245 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002246
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002248 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002249 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002250 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002251 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002252 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002253 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002254 newTouchedWindowHandle =
2255 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002256
Prabir Pradhan5735a322022-04-11 17:23:34 +00002257 // Verify targeted injection.
2258 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2259 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002260 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002261 newTouchedWindowHandle = nullptr;
2262 goto Failed;
2263 }
2264
Vishnu Nair062a8672021-09-03 16:07:44 -07002265 // Drop touch events if requested by input feature
2266 if (newTouchedWindowHandle != nullptr &&
2267 shouldDropInput(entry, newTouchedWindowHandle)) {
2268 newTouchedWindowHandle = nullptr;
2269 }
2270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002271 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2272 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002273 if (DEBUG_FOCUS) {
2274 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2275 oldTouchedWindowHandle->getName().c_str(),
2276 newTouchedWindowHandle->getName().c_str(), displayId);
2277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002279 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002280 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282
2283 // Make a slippery entrance into the new window.
2284 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002285 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 }
2287
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002288 ftl::Flags<InputTarget::Flags> targetFlags =
2289 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002290 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002291 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002294 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002297 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002298 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002299 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301
2302 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002303 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002304 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2305 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307 }
2308 }
2309
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002310 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002312 // Let the previous window know that the hover sequence is over, unless we already did
2313 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002314 if (mLastHoverWindowHandle != nullptr &&
2315 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2316 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002317 if (DEBUG_HOVER) {
2318 ALOGD("Sending hover exit event to window %s.",
2319 mLastHoverWindowHandle->getName().c_str());
2320 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002321 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002322 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2323 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Garfield Tandf26e862020-07-01 20:18:19 -07002326 // Let the new window know that the hover sequence is starting, unless we already did it
2327 // when dispatching it as is to newTouchedWindowHandle.
2328 if (newHoverWindowHandle != nullptr &&
2329 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2330 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002331 if (DEBUG_HOVER) {
2332 ALOGD("Sending hover enter event to window %s.",
2333 newHoverWindowHandle->getName().c_str());
2334 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002335 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002336 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002337 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
2339 }
2340
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002341 // Ensure that we have at least one foreground window or at least one window that cannot be a
2342 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2343 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2344 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002345 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2346 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002347 return !canReceiveForegroundTouches(
2348 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002349 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002350 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002351 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2352 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002353 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002354 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356
Prabir Pradhan5735a322022-04-11 17:23:34 +00002357 // Ensure that all touched windows are valid for injection.
2358 if (entry.injectionState != nullptr) {
2359 std::string errs;
2360 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002361 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002362 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2363 // dispatched to any uid, since the coords will be zeroed out later.
2364 continue;
2365 }
2366 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2367 if (err) errs += "\n - " + *err;
2368 }
2369 if (!errs.empty()) {
2370 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2371 "%d:%s",
2372 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002373 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002374 goto Failed;
2375 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002376 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 // Check whether windows listening for outside touches are owned by the same UID. If it is
2379 // set the policy flag that we will not reveal coordinate information to this window.
2380 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002381 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002383 if (foregroundWindowHandle) {
2384 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002385 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002386 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002387 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2388 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2389 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002391 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
2394 }
2395 }
2396 }
2397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // If this is the first pointer going down and the touched window has a wallpaper
2399 // then also add the touched wallpaper windows so they are locked in for the duration
2400 // of the touch gesture.
2401 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2402 // engine only supports touch events. We would need to add a mechanism similar
2403 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2404 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002405 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002406 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002407 if (foregroundWindowHandle &&
2408 foregroundWindowHandle->getInfo()->inputConfig.test(
2409 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002410 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002411 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002412 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2413 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002415 windowHandle->getInfo()->inputConfig.test(
2416 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002417 tempTouchState.addOrUpdateWindow(windowHandle,
2418 InputTarget::Flags::WINDOW_IS_OBSCURED |
2419 InputTarget::Flags::
2420 WINDOW_IS_PARTIALLY_OBSCURED |
2421 InputTarget::Flags::DISPATCH_AS_IS,
2422 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
2424 }
2425 }
2426 }
2427
2428 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002429 touchedWindows = tempTouchState.windows;
2430 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431
2432 // Drop the outside or hover touch windows since we will not care about them
2433 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002434 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435
2436Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002438 if (switchedDevice) {
2439 if (DEBUG_FOCUS) {
2440 ALOGD("Conflicting pointer actions: Switched to a different device.");
2441 }
2442 *outConflictingPointerActions = true;
2443 }
2444
2445 if (isHoverAction) {
2446 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002447 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002448 ALOGD_IF(DEBUG_FOCUS,
2449 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002450 *outConflictingPointerActions = true;
2451 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002452 tempTouchState.reset();
2453 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2454 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2455 tempTouchState.deviceId = entry.deviceId;
2456 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002457 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002458 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2459 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2460 // All pointers up or canceled.
2461 tempTouchState.reset();
2462 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2463 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002464 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002465 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002466 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002467 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002468 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2469 // One pointer went up.
2470 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2471 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002473 for (size_t i = 0; i < tempTouchState.windows.size();) {
2474 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2475 touchedWindow.pointerIds.clearBit(pointerId);
2476 if (touchedWindow.pointerIds.isEmpty()) {
2477 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2478 continue;
2479 }
2480 i += 1;
2481 }
2482 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2483 // If no split, we suppose all touched windows should receive pointer down.
2484 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2485 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2486 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2487 // Ignore drag window for it should just track one pointer.
2488 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2489 continue;
2490 }
2491 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 }
2494
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002495 // Save changes unless the action was scroll in which case the temporary touch
2496 // state was only valid for this one action.
2497 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002498 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002499 mTouchStatesByDisplay[displayId] = tempTouchState;
2500 } else {
2501 mTouchStatesByDisplay.erase(displayId);
2502 }
2503 }
2504
2505 // Update hover state.
2506 mLastHoverWindowHandle = newHoverWindowHandle;
2507
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002508 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509}
2510
arthurhung6d4bed92021-03-17 11:59:33 +08002511void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002512 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2513 // have an explicit reason to support it.
2514 constexpr bool isStylus = false;
2515
chaviw98318de2021-05-19 16:45:23 -05002516 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002517 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002518 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002519 if (dropWindow) {
2520 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002521 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002522 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002523 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002524 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002525 }
2526 mDragState.reset();
2527}
2528
2529void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002530 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002531 return;
2532 }
2533
arthurhung6d4bed92021-03-17 11:59:33 +08002534 if (!mDragState->isStartDrag) {
2535 mDragState->isStartDrag = true;
2536 mDragState->isStylusButtonDownAtStart =
2537 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2538 }
2539
Arthur Hung54745652022-04-20 07:17:41 +00002540 // Find the pointer index by id.
2541 int32_t pointerIndex = 0;
2542 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2543 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2544 if (pointerProperties.id == mDragState->pointerId) {
2545 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002546 }
Arthur Hung54745652022-04-20 07:17:41 +00002547 }
arthurhung6d4bed92021-03-17 11:59:33 +08002548
Arthur Hung54745652022-04-20 07:17:41 +00002549 if (uint32_t(pointerIndex) == entry.pointerCount) {
2550 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002551 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002552 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002553 return;
2554 }
2555
2556 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2557 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2558 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2559
2560 switch (maskedAction) {
2561 case AMOTION_EVENT_ACTION_MOVE: {
2562 // Handle the special case : stylus button no longer pressed.
2563 bool isStylusButtonDown =
2564 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2565 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2566 finishDragAndDrop(entry.displayId, x, y);
2567 return;
2568 }
2569
2570 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2571 // until we have an explicit reason to support it.
2572 constexpr bool isStylus = false;
2573
2574 const sp<WindowInfoHandle> hoverWindowHandle =
2575 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2576 isStylus, false /*addOutsideTargets*/,
2577 true /*ignoreDragWindow*/);
2578 // enqueue drag exit if needed.
2579 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2580 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2581 if (mDragState->dragHoverWindowHandle != nullptr) {
2582 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2583 y);
2584 }
2585 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2586 }
2587 // enqueue drag location if needed.
2588 if (hoverWindowHandle != nullptr) {
2589 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2590 }
2591 break;
2592 }
2593
2594 case AMOTION_EVENT_ACTION_POINTER_UP:
2595 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2596 break;
2597 }
2598 // The drag pointer is up.
2599 [[fallthrough]];
2600 case AMOTION_EVENT_ACTION_UP:
2601 finishDragAndDrop(entry.displayId, x, y);
2602 break;
2603 case AMOTION_EVENT_ACTION_CANCEL: {
2604 ALOGD("Receiving cancel when drag and drop.");
2605 sendDropWindowCommandLocked(nullptr, 0, 0);
2606 mDragState.reset();
2607 break;
2608 }
arthurhungb89ccb02020-12-30 16:19:01 +08002609 }
2610}
2611
chaviw98318de2021-05-19 16:45:23 -05002612void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002613 ftl::Flags<InputTarget::Flags> targetFlags,
2614 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002615 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002616 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002617 std::vector<InputTarget>::iterator it =
2618 std::find_if(inputTargets.begin(), inputTargets.end(),
2619 [&windowHandle](const InputTarget& inputTarget) {
2620 return inputTarget.inputChannel->getConnectionToken() ==
2621 windowHandle->getToken();
2622 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002623
chaviw98318de2021-05-19 16:45:23 -05002624 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002625
2626 if (it == inputTargets.end()) {
2627 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002628 std::shared_ptr<InputChannel> inputChannel =
2629 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002630 if (inputChannel == nullptr) {
2631 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2632 return;
2633 }
2634 inputTarget.inputChannel = inputChannel;
2635 inputTarget.flags = targetFlags;
2636 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002637 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002638 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2639 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002640 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002641 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002642 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002643 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002644 inputTargets.push_back(inputTarget);
2645 it = inputTargets.end() - 1;
2646 }
2647
2648 ALOG_ASSERT(it->flags == targetFlags);
2649 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2650
chaviw1ff3d1e2020-07-01 15:53:47 -07002651 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652}
2653
Michael Wright3dd60e22019-03-27 22:06:44 +00002654void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002655 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002656 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2657 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002658
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002659 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2660 InputTarget target;
2661 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002662 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002663 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2664 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002665 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2666 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002667 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002668 target.setDefaultPointerTransform(target.displayTransform);
2669 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 }
2671}
2672
Robert Carrc9bf1d32020-04-13 17:21:08 -07002673/**
2674 * Indicate whether one window handle should be considered as obscuring
2675 * another window handle. We only check a few preconditions. Actually
2676 * checking the bounds is left to the caller.
2677 */
chaviw98318de2021-05-19 16:45:23 -05002678static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2679 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002680 // Compare by token so cloned layers aren't counted
2681 if (haveSameToken(windowHandle, otherHandle)) {
2682 return false;
2683 }
2684 auto info = windowHandle->getInfo();
2685 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002686 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002687 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002688 } else if (otherInfo->alpha == 0 &&
2689 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002690 // Those act as if they were invisible, so we don't need to flag them.
2691 // We do want to potentially flag touchable windows even if they have 0
2692 // opacity, since they can consume touches and alter the effects of the
2693 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002694 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002695 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2696 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002697 } else if (info->ownerUid == otherInfo->ownerUid) {
2698 // If ownerUid is the same we don't generate occlusion events as there
2699 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002700 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002701 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002702 return false;
2703 } else if (otherInfo->displayId != info->displayId) {
2704 return false;
2705 }
2706 return true;
2707}
2708
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002709/**
2710 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2711 * untrusted, one should check:
2712 *
2713 * 1. If result.hasBlockingOcclusion is true.
2714 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2715 * BLOCK_UNTRUSTED.
2716 *
2717 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2718 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2719 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2720 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2721 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2722 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2723 *
2724 * If neither of those is true, then it means the touch can be allowed.
2725 */
2726InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002727 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2728 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002729 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002730 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002731 TouchOcclusionInfo info;
2732 info.hasBlockingOcclusion = false;
2733 info.obscuringOpacity = 0;
2734 info.obscuringUid = -1;
2735 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002736 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002737 if (windowHandle == otherHandle) {
2738 break; // All future windows are below us. Exit early.
2739 }
chaviw98318de2021-05-19 16:45:23 -05002740 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002741 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2742 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002743 if (DEBUG_TOUCH_OCCLUSION) {
2744 info.debugInfo.push_back(
2745 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2746 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002747 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2748 // we perform the checks below to see if the touch can be propagated or not based on the
2749 // window's touch occlusion mode
2750 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2751 info.hasBlockingOcclusion = true;
2752 info.obscuringUid = otherInfo->ownerUid;
2753 info.obscuringPackage = otherInfo->packageName;
2754 break;
2755 }
2756 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2757 uint32_t uid = otherInfo->ownerUid;
2758 float opacity =
2759 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2760 // Given windows A and B:
2761 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2762 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2763 opacityByUid[uid] = opacity;
2764 if (opacity > info.obscuringOpacity) {
2765 info.obscuringOpacity = opacity;
2766 info.obscuringUid = uid;
2767 info.obscuringPackage = otherInfo->packageName;
2768 }
2769 }
2770 }
2771 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002772 if (DEBUG_TOUCH_OCCLUSION) {
2773 info.debugInfo.push_back(
2774 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2775 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002776 return info;
2777}
2778
chaviw98318de2021-05-19 16:45:23 -05002779std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002780 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002781 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2782 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2783 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2784 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002785 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2786 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2787 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2788 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2789 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002790 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002791 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002792}
2793
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002794bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2795 if (occlusionInfo.hasBlockingOcclusion) {
2796 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2797 occlusionInfo.obscuringUid);
2798 return false;
2799 }
2800 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2801 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2802 "%.2f, maximum allowed = %.2f)",
2803 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2804 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2805 return false;
2806 }
2807 return true;
2808}
2809
chaviw98318de2021-05-19 16:45:23 -05002810bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002811 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002813 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2814 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002815 if (windowHandle == otherHandle) {
2816 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 }
chaviw98318de2021-05-19 16:45:23 -05002818 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002819 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002820 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 return true;
2822 }
2823 }
2824 return false;
2825}
2826
chaviw98318de2021-05-19 16:45:23 -05002827bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002828 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002829 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2830 const WindowInfo* windowInfo = windowHandle->getInfo();
2831 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002832 if (windowHandle == otherHandle) {
2833 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002834 }
chaviw98318de2021-05-19 16:45:23 -05002835 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002836 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002837 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002838 return true;
2839 }
2840 }
2841 return false;
2842}
2843
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002844std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002845 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002846 if (applicationHandle != nullptr) {
2847 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002848 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 } else {
2850 return applicationHandle->getName();
2851 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002852 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002853 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002855 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 }
2857}
2858
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002859void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002860 if (!isUserActivityEvent(eventEntry)) {
2861 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002862 return;
2863 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002864 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002865 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002866 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002867 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002868 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002869 if (DEBUG_DISPATCH_CYCLE) {
2870 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 return;
2873 }
2874 }
2875
2876 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002877 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002878 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002879 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2880 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 return;
2882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 eventType = USER_ACTIVITY_EVENT_TOUCH;
2886 }
2887 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002889 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002890 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2891 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 return;
2893 }
2894 eventType = USER_ACTIVITY_EVENT_BUTTON;
2895 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002897 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002898 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002899 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002900 break;
2901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 }
2903
Prabir Pradhancef936d2021-07-21 16:17:52 +00002904 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2905 REQUIRES(mLock) {
2906 scoped_unlock unlock(mLock);
2907 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2908 };
2909 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910}
2911
2912void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002914 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002915 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002916 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002918 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002919 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002920 ATRACE_NAME(message.c_str());
2921 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002922 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002923 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002924 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002925 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002926 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2927 inputTarget.getPointerInfoString().c_str());
2928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
2930 // Skip this event if the connection status is not normal.
2931 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002932 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002933 if (DEBUG_DISPATCH_CYCLE) {
2934 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002935 connection->getInputChannelName().c_str(),
2936 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 return;
2939 }
2940
2941 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002942 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002943 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002944 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002945 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002947 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002948 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002949 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2950 "Splitting motion events requires a down time to be set for the "
2951 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002953 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2954 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 if (!splitMotionEntry) {
2956 return; // split event was dropped
2957 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002958 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2959 std::string reason = std::string("reason=pointer cancel on split window");
2960 android_log_event_list(LOGTAG_INPUT_CANCEL)
2961 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2962 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002963 if (DEBUG_FOCUS) {
2964 ALOGD("channel '%s' ~ Split motion event.",
2965 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002966 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002967 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002968 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2969 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 return;
2971 }
2972 }
2973
2974 // Not splitting. Enqueue dispatch entries for the event as is.
2975 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2976}
2977
2978void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002981 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002982 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002984 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002985 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002986 ATRACE_NAME(message.c_str());
2987 }
2988
hongzuo liu95785e22022-09-06 02:51:35 +00002989 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990
2991 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002992 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002993 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002994 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002995 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002996 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002997 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002998 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002999 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003000 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003001 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003002 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003003 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
3005 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003006 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 startDispatchCycleLocked(currentTime, connection);
3008 }
3009}
3010
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003012 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003013 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003014 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003015 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3017 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003018 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003019 ATRACE_NAME(message.c_str());
3020 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003021 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3022 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 return;
3024 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003025
3026 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3027 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028
3029 // This is a new event.
3030 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003031 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003032 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003034 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3035 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003036 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003038 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003039 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003040 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003041 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 dispatchEntry->resolvedAction = keyEntry.action;
3043 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3046 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003047 if (DEBUG_DISPATCH_CYCLE) {
3048 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3049 "event",
3050 connection->getInputChannelName().c_str());
3051 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 return; // skip the inconsistent event
3053 }
3054 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003057 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003058 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003059 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3060 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3061 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3062 static_cast<int32_t>(IdGenerator::Source::OTHER);
3063 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003064 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003066 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003067 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003068 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003070 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003071 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003072 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003073 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3074 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003075 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003076 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 }
3078 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003079 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3080 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003081 if (DEBUG_DISPATCH_CYCLE) {
3082 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3083 "enter event",
3084 connection->getInputChannelName().c_str());
3085 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003086 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3087 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003091 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003092 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3094 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003095 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003096 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3100 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003101 if (DEBUG_DISPATCH_CYCLE) {
3102 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3103 "event",
3104 connection->getInputChannelName().c_str());
3105 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 return; // skip the inconsistent event
3107 }
3108
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003109 dispatchEntry->resolvedEventId =
3110 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3111 ? mIdGenerator.nextId()
3112 : motionEntry.id;
3113 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3114 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3115 ") to MotionEvent(id=0x%" PRIx32 ").",
3116 motionEntry.id, dispatchEntry->resolvedEventId);
3117 ATRACE_NAME(message.c_str());
3118 }
3119
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003120 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3121 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3122 // Skip reporting pointer down outside focus to the policy.
3123 break;
3124 }
3125
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003126 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003127 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128
3129 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003131 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003132 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003133 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3134 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003135 break;
3136 }
Chris Yef59a2f42020-10-16 12:55:26 -07003137 case EventEntry::Type::SENSOR: {
3138 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3139 break;
3140 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003141 case EventEntry::Type::CONFIGURATION_CHANGED:
3142 case EventEntry::Type::DEVICE_RESET: {
3143 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003144 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003145 break;
3146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
3149 // Remember that we are waiting for this dispatch to complete.
3150 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003151 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
3153
3154 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003155 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003156 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003157}
3158
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003159/**
3160 * This function is purely for debugging. It helps us understand where the user interaction
3161 * was taking place. For example, if user is touching launcher, we will see a log that user
3162 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3163 * We will see both launcher and wallpaper in that list.
3164 * Once the interaction with a particular set of connections starts, no new logs will be printed
3165 * until the set of interacted connections changes.
3166 *
3167 * The following items are skipped, to reduce the logspam:
3168 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3169 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3170 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3171 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3172 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003173 */
3174void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3175 const std::vector<InputTarget>& targets) {
3176 // Skip ACTION_UP events, and all events other than keys and motions
3177 if (entry.type == EventEntry::Type::KEY) {
3178 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3179 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3180 return;
3181 }
3182 } else if (entry.type == EventEntry::Type::MOTION) {
3183 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3184 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3185 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3186 return;
3187 }
3188 } else {
3189 return; // Not a key or a motion
3190 }
3191
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003192 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003193 std::vector<sp<Connection>> newConnections;
3194 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003195 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003196 continue; // Skip windows that receive ACTION_OUTSIDE
3197 }
3198
3199 sp<IBinder> token = target.inputChannel->getConnectionToken();
3200 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003201 if (connection == nullptr) {
3202 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003203 }
3204 newConnectionTokens.insert(std::move(token));
3205 newConnections.emplace_back(connection);
3206 }
3207 if (newConnectionTokens == mInteractionConnectionTokens) {
3208 return; // no change
3209 }
3210 mInteractionConnectionTokens = newConnectionTokens;
3211
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003212 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003213 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003214 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003215 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003216 std::string message = "Interaction with: " + targetList;
3217 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003218 message += "<none>";
3219 }
3220 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3221}
3222
chaviwfd6d3512019-03-25 13:23:49 -07003223void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003224 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003225 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003226 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3227 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003228 return;
3229 }
3230
Vishnu Nairc519ff72021-01-21 08:23:08 -08003231 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003232 if (focusedToken == token) {
3233 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003234 return;
3235 }
3236
Prabir Pradhancef936d2021-07-21 16:17:52 +00003237 auto command = [this, token]() REQUIRES(mLock) {
3238 scoped_unlock unlock(mLock);
3239 mPolicy->onPointerDownOutsideFocus(token);
3240 };
3241 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242}
3243
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003244status_t InputDispatcher::publishMotionEvent(Connection& connection,
3245 DispatchEntry& dispatchEntry) const {
3246 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3247 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3248
3249 PointerCoords scaledCoords[MAX_POINTERS];
3250 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3251
3252 // Set the X and Y offset and X and Y scale depending on the input source.
3253 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003254 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003255 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3256 if (globalScaleFactor != 1.0f) {
3257 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3258 scaledCoords[i] = motionEntry.pointerCoords[i];
3259 // Don't apply window scale here since we don't want scale to affect raw
3260 // coordinates. The scale will be sent back to the client and applied
3261 // later when requesting relative coordinates.
3262 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3263 1 /* windowYScale */);
3264 }
3265 usingCoords = scaledCoords;
3266 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003267 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003268 // We don't want the dispatch target to know the coordinates
3269 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3270 scaledCoords[i].clear();
3271 }
3272 usingCoords = scaledCoords;
3273 }
3274
3275 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3276
3277 // Publish the motion event.
3278 return connection.inputPublisher
3279 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3280 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3281 std::move(hmac), dispatchEntry.resolvedAction,
3282 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3283 motionEntry.edgeFlags, motionEntry.metaState,
3284 motionEntry.buttonState, motionEntry.classification,
3285 dispatchEntry.transform, motionEntry.xPrecision,
3286 motionEntry.yPrecision, motionEntry.xCursorPosition,
3287 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3288 motionEntry.downTime, motionEntry.eventTime,
3289 motionEntry.pointerCount, motionEntry.pointerProperties,
3290 usingCoords);
3291}
3292
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003295 if (ATRACE_ENABLED()) {
3296 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003298 ATRACE_NAME(message.c_str());
3299 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003300 if (DEBUG_DISPATCH_CYCLE) {
3301 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003304 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003305 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003307 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003308 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309
3310 // Publish the event.
3311 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003312 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3313 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003314 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3316 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003319 status = connection->inputPublisher
3320 .publishKeyEvent(dispatchEntry->seq,
3321 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3322 keyEntry.source, keyEntry.displayId,
3323 std::move(hmac), dispatchEntry->resolvedAction,
3324 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3325 keyEntry.scanCode, keyEntry.metaState,
3326 keyEntry.repeatCount, keyEntry.downTime,
3327 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 }
3330
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003331 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003332 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 break;
3334 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003335
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003336 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003337 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003338 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003339 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003340 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003341 break;
3342 }
3343
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003344 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3345 const TouchModeEntry& touchModeEntry =
3346 static_cast<const TouchModeEntry&>(eventEntry);
3347 status = connection->inputPublisher
3348 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3349 touchModeEntry.inTouchMode);
3350
3351 break;
3352 }
3353
Prabir Pradhan99987712020-11-10 18:43:05 -08003354 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3355 const auto& captureEntry =
3356 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3357 status = connection->inputPublisher
3358 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003359 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003360 break;
3361 }
3362
arthurhungb89ccb02020-12-30 16:19:01 +08003363 case EventEntry::Type::DRAG: {
3364 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3365 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3366 dragEntry.id, dragEntry.x,
3367 dragEntry.y,
3368 dragEntry.isExiting);
3369 break;
3370 }
3371
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003372 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003373 case EventEntry::Type::DEVICE_RESET:
3374 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003375 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003376 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
3380
3381 // Check the result.
3382 if (status) {
3383 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003384 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 "This is unexpected because the wait queue is empty, so the pipe "
3387 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003388 "event to it, status=%s(%d)",
3389 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3390 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3392 } else {
3393 // Pipe is full and we are waiting for the app to finish process some events
3394 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003395 if (DEBUG_DISPATCH_CYCLE) {
3396 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3397 "waiting for the application to catch up",
3398 connection->getInputChannelName().c_str());
3399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
3401 } else {
3402 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003403 "status=%s(%d)",
3404 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3405 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3407 }
3408 return;
3409 }
3410
3411 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003412 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3413 connection->outboundQueue.end(),
3414 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003415 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003416 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003417 if (connection->responsive) {
3418 mAnrTracker.insert(dispatchEntry->timeoutTime,
3419 connection->inputChannel->getConnectionToken());
3420 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003421 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 }
3423}
3424
chaviw09c8d2d2020-08-24 15:48:26 -07003425std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3426 size_t size;
3427 switch (event.type) {
3428 case VerifiedInputEvent::Type::KEY: {
3429 size = sizeof(VerifiedKeyEvent);
3430 break;
3431 }
3432 case VerifiedInputEvent::Type::MOTION: {
3433 size = sizeof(VerifiedMotionEvent);
3434 break;
3435 }
3436 }
3437 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3438 return mHmacKeyManager.sign(start, size);
3439}
3440
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003441const std::array<uint8_t, 32> InputDispatcher::getSignature(
3442 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003443 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3444 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003445 // Only sign events up and down events as the purely move events
3446 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003447 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003448 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003449
3450 VerifiedMotionEvent verifiedEvent =
3451 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3452 verifiedEvent.actionMasked = actionMasked;
3453 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3454 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003455}
3456
3457const std::array<uint8_t, 32> InputDispatcher::getSignature(
3458 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3459 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3460 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3461 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003462 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003463}
3464
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003466 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003467 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003468 if (DEBUG_DISPATCH_CYCLE) {
3469 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3470 connection->getInputChannelName().c_str(), seq, toString(handled));
3471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003473 if (connection->status == Connection::Status::BROKEN ||
3474 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 return;
3476 }
3477
3478 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003479 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3480 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3481 };
3482 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483}
3484
3485void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003486 const sp<Connection>& connection,
3487 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003488 if (DEBUG_DISPATCH_CYCLE) {
3489 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3490 connection->getInputChannelName().c_str(), toString(notify));
3491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492
3493 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003494 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003495 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003496 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003497 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498
3499 // The connection appears to be unrecoverably broken.
3500 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003501 if (connection->status == Connection::Status::NORMAL) {
3502 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503
3504 if (notify) {
3505 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003506 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3507 connection->getInputChannelName().c_str());
3508
3509 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003510 scoped_unlock unlock(mLock);
3511 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3512 };
3513 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 }
3515 }
3516}
3517
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003518void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3519 while (!queue.empty()) {
3520 DispatchEntry* dispatchEntry = queue.front();
3521 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003522 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
3524}
3525
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003526void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003528 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
3530 delete dispatchEntry;
3531}
3532
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003533int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3534 std::scoped_lock _l(mLock);
3535 sp<Connection> connection = getConnectionLocked(connectionToken);
3536 if (connection == nullptr) {
3537 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3538 connectionToken.get(), events);
3539 return 0; // remove the callback
3540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003542 bool notify;
3543 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3544 if (!(events & ALOOPER_EVENT_INPUT)) {
3545 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3546 "events=0x%x",
3547 connection->getInputChannelName().c_str(), events);
3548 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 }
3550
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003551 nsecs_t currentTime = now();
3552 bool gotOne = false;
3553 status_t status = OK;
3554 for (;;) {
3555 Result<InputPublisher::ConsumerResponse> result =
3556 connection->inputPublisher.receiveConsumerResponse();
3557 if (!result.ok()) {
3558 status = result.error().code();
3559 break;
3560 }
3561
3562 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3563 const InputPublisher::Finished& finish =
3564 std::get<InputPublisher::Finished>(*result);
3565 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3566 finish.consumeTime);
3567 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003568 if (shouldReportMetricsForConnection(*connection)) {
3569 const InputPublisher::Timeline& timeline =
3570 std::get<InputPublisher::Timeline>(*result);
3571 mLatencyTracker
3572 .trackGraphicsLatency(timeline.inputEventId,
3573 connection->inputChannel->getConnectionToken(),
3574 std::move(timeline.graphicsTimeline));
3575 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003576 }
3577 gotOne = true;
3578 }
3579 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003580 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003581 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 return 1;
3583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 }
3585
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003586 notify = status != DEAD_OBJECT || !connection->monitor;
3587 if (notify) {
3588 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3589 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3590 status);
3591 }
3592 } else {
3593 // Monitor channels are never explicitly unregistered.
3594 // We do it automatically when the remote endpoint is closed so don't warn about them.
3595 const bool stillHaveWindowHandle =
3596 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3597 notify = !connection->monitor && stillHaveWindowHandle;
3598 if (notify) {
3599 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3600 connection->getInputChannelName().c_str(), events);
3601 }
3602 }
3603
3604 // Remove the channel.
3605 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3606 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607}
3608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003609void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003611 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003612 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 }
3614}
3615
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003616void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003617 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003618 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003619 for (const Monitor& monitor : monitors) {
3620 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003621 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003622 }
3623}
3624
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003626 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003627 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003628 if (connection == nullptr) {
3629 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003631
3632 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633}
3634
3635void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3636 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003637 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 return;
3639 }
3640
3641 nsecs_t currentTime = now();
3642
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003643 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003644 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003646 if (cancelationEvents.empty()) {
3647 return;
3648 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003649 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3650 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3651 "with reality: %s, mode=%d.",
3652 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3653 options.mode);
3654 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003655
Arthur Hungb3307ee2021-10-14 10:57:37 +00003656 std::string reason = std::string("reason=").append(options.reason);
3657 android_log_event_list(LOGTAG_INPUT_CANCEL)
3658 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3659
Svet Ganov5d3bc372020-01-26 23:11:07 -08003660 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003661 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003662 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3663 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003664 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003665 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003666 target.globalScaleFactor = windowInfo->globalScaleFactor;
3667 }
3668 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003669 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670
hongzuo liu95785e22022-09-06 02:51:35 +00003671 const bool wasEmpty = connection->outboundQueue.empty();
3672
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003673 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003674 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003675 switch (cancelationEventEntry->type) {
3676 case EventEntry::Type::KEY: {
3677 logOutboundKeyDetails("cancel - ",
3678 static_cast<const KeyEntry&>(*cancelationEventEntry));
3679 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003681 case EventEntry::Type::MOTION: {
3682 logOutboundMotionDetails("cancel - ",
3683 static_cast<const MotionEntry&>(*cancelationEventEntry));
3684 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003686 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003687 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003688 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3689 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003690 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003691 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003692 break;
3693 }
3694 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003695 case EventEntry::Type::DEVICE_RESET:
3696 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003697 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003698 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003699 break;
3700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003703 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003704 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003706
hongzuo liu95785e22022-09-06 02:51:35 +00003707 // If the outbound queue was previously empty, start the dispatch cycle going.
3708 if (wasEmpty && !connection->outboundQueue.empty()) {
3709 startDispatchCycleLocked(currentTime, connection);
3710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711}
3712
Svet Ganov5d3bc372020-01-26 23:11:07 -08003713void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003714 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003715 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716 return;
3717 }
3718
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003719 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003720 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003721
3722 if (downEvents.empty()) {
3723 return;
3724 }
3725
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003726 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003727 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3728 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003729 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003730
3731 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003732 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003733 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3734 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003735 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003736 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003737 target.globalScaleFactor = windowInfo->globalScaleFactor;
3738 }
3739 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003740 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003741
hongzuo liu95785e22022-09-06 02:51:35 +00003742 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003743 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003744 switch (downEventEntry->type) {
3745 case EventEntry::Type::MOTION: {
3746 logOutboundMotionDetails("down - ",
3747 static_cast<const MotionEntry&>(*downEventEntry));
3748 break;
3749 }
3750
3751 case EventEntry::Type::KEY:
3752 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003753 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003754 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003755 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003756 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003757 case EventEntry::Type::SENSOR:
3758 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003759 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003760 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003761 break;
3762 }
3763 }
3764
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003765 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003766 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003767 }
3768
hongzuo liu95785e22022-09-06 02:51:35 +00003769 // If the outbound queue was previously empty, start the dispatch cycle going.
3770 if (wasEmpty && !connection->outboundQueue.empty()) {
3771 startDispatchCycleLocked(downTime, connection);
3772 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003773}
3774
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003775std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003776 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 ALOG_ASSERT(pointerIds.value != 0);
3778
3779 uint32_t splitPointerIndexMap[MAX_POINTERS];
3780 PointerProperties splitPointerProperties[MAX_POINTERS];
3781 PointerCoords splitPointerCoords[MAX_POINTERS];
3782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003783 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 uint32_t splitPointerCount = 0;
3785
3786 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003789 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 uint32_t pointerId = uint32_t(pointerProperties.id);
3791 if (pointerIds.hasBit(pointerId)) {
3792 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3793 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3794 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003795 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 splitPointerCount += 1;
3797 }
3798 }
3799
3800 if (splitPointerCount != pointerIds.count()) {
3801 // This is bad. We are missing some of the pointers that we expected to deliver.
3802 // Most likely this indicates that we received an ACTION_MOVE events that has
3803 // different pointer ids than we expected based on the previous ACTION_DOWN
3804 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3805 // in this way.
3806 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003807 "we expected there to be %d pointers. This probably means we received "
3808 "a broken sequence of pointer ids from the input device.",
3809 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003810 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003813 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003815 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3816 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3818 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003819 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 uint32_t pointerId = uint32_t(pointerProperties.id);
3821 if (pointerIds.hasBit(pointerId)) {
3822 if (pointerIds.count() == 1) {
3823 // The first/last pointer went down/up.
3824 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003826 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3827 ? AMOTION_EVENT_ACTION_CANCEL
3828 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 } else {
3830 // A secondary pointer went down/up.
3831 uint32_t splitPointerIndex = 0;
3832 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3833 splitPointerIndex += 1;
3834 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003835 action = maskedAction |
3836 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 }
3838 } else {
3839 // An unrelated pointer changed.
3840 action = AMOTION_EVENT_ACTION_MOVE;
3841 }
3842 }
3843
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003844 if (action == AMOTION_EVENT_ACTION_DOWN) {
3845 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3846 "Split motion event has mismatching downTime and eventTime for "
3847 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3848 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3849 }
3850
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003851 int32_t newId = mIdGenerator.nextId();
3852 if (ATRACE_ENABLED()) {
3853 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3854 ") to MotionEvent(id=0x%" PRIx32 ").",
3855 originalMotionEntry.id, newId);
3856 ATRACE_NAME(message.c_str());
3857 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003858 std::unique_ptr<MotionEntry> splitMotionEntry =
3859 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3860 originalMotionEntry.deviceId, originalMotionEntry.source,
3861 originalMotionEntry.displayId,
3862 originalMotionEntry.policyFlags, action,
3863 originalMotionEntry.actionButton,
3864 originalMotionEntry.flags, originalMotionEntry.metaState,
3865 originalMotionEntry.buttonState,
3866 originalMotionEntry.classification,
3867 originalMotionEntry.edgeFlags,
3868 originalMotionEntry.xPrecision,
3869 originalMotionEntry.yPrecision,
3870 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003871 originalMotionEntry.yCursorPosition, splitDownTime,
3872 splitPointerCount, splitPointerProperties,
3873 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003875 if (originalMotionEntry.injectionState) {
3876 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 splitMotionEntry->injectionState->refCount += 1;
3878 }
3879
3880 return splitMotionEntry;
3881}
3882
3883void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003884 if (DEBUG_INBOUND_EVENT_DETAILS) {
3885 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Antonio Kantekf16f2832021-09-28 04:39:20 +00003888 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003890 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003892 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3893 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3894 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 } // release lock
3896
3897 if (needWake) {
3898 mLooper->wake();
3899 }
3900}
3901
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003902/**
3903 * If one of the meta shortcuts is detected, process them here:
3904 * Meta + Backspace -> generate BACK
3905 * Meta + Enter -> generate HOME
3906 * This will potentially overwrite keyCode and metaState.
3907 */
3908void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003909 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003910 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3911 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3912 if (keyCode == AKEYCODE_DEL) {
3913 newKeyCode = AKEYCODE_BACK;
3914 } else if (keyCode == AKEYCODE_ENTER) {
3915 newKeyCode = AKEYCODE_HOME;
3916 }
3917 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003918 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003919 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003920 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003921 keyCode = newKeyCode;
3922 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3923 }
3924 } else if (action == AKEY_EVENT_ACTION_UP) {
3925 // In order to maintain a consistent stream of up and down events, check to see if the key
3926 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3927 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003928 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003929 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003930 auto replacementIt = mReplacedKeys.find(replacement);
3931 if (replacementIt != mReplacedKeys.end()) {
3932 keyCode = replacementIt->second;
3933 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003934 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3935 }
3936 }
3937}
3938
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003940 if (DEBUG_INBOUND_EVENT_DETAILS) {
3941 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3942 "policyFlags=0x%x, action=0x%x, "
3943 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3944 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3945 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3946 args->downTime);
3947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948 if (!validateKeyEvent(args->action)) {
3949 return;
3950 }
3951
3952 uint32_t policyFlags = args->policyFlags;
3953 int32_t flags = args->flags;
3954 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003955 // InputDispatcher tracks and generates key repeats on behalf of
3956 // whatever notifies it, so repeatCount should always be set to 0
3957 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3959 policyFlags |= POLICY_FLAG_VIRTUAL;
3960 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 if (policyFlags & POLICY_FLAG_FUNCTION) {
3963 metaState |= AMETA_FUNCTION_ON;
3964 }
3965
3966 policyFlags |= POLICY_FLAG_TRUSTED;
3967
Michael Wright78f24442014-08-06 15:55:28 -07003968 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003969 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003970
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003972 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003973 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3974 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
Michael Wright2b3c3302018-03-02 17:19:13 +00003976 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003978 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3979 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982
Antonio Kantekf16f2832021-09-28 04:39:20 +00003983 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 { // acquire lock
3985 mLock.lock();
3986
3987 if (shouldSendKeyToInputFilterLocked(args)) {
3988 mLock.unlock();
3989
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003990 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3992 return; // event was consumed by the filter
3993 }
3994
3995 mLock.lock();
3996 }
3997
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003998 std::unique_ptr<KeyEntry> newEntry =
3999 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4000 args->displayId, policyFlags, args->action, flags,
4001 keyCode, args->scanCode, metaState, repeatCount,
4002 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004004 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 mLock.unlock();
4006 } // release lock
4007
4008 if (needWake) {
4009 mLooper->wake();
4010 }
4011}
4012
4013bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4014 return mInputFilterEnabled;
4015}
4016
4017void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004018 if (DEBUG_INBOUND_EVENT_DETAILS) {
4019 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4020 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004021 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004022 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4023 "yCursorPosition=%f, downTime=%" PRId64,
4024 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004025 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4026 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4027 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4028 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004029 for (uint32_t i = 0; i < args->pointerCount; i++) {
4030 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4031 "x=%f, y=%f, pressure=%f, size=%f, "
4032 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4033 "orientation=%f",
4034 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4035 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4036 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4037 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4038 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4039 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4040 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4041 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4042 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4043 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004046 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4047 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 return;
4049 }
4050
4051 uint32_t policyFlags = args->policyFlags;
4052 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004053
4054 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004055 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004056 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4057 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060
Antonio Kantekf16f2832021-09-28 04:39:20 +00004061 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 { // acquire lock
4063 mLock.lock();
4064
4065 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004066 ui::Transform displayTransform;
4067 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4068 displayTransform = it->second.transform;
4069 }
4070
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 mLock.unlock();
4072
4073 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004074 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4075 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004076 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004077 displayTransform, args->xPrecision, args->yPrecision,
4078 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004079 args->downTime, args->eventTime, args->pointerCount,
4080 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
4082 policyFlags |= POLICY_FLAG_FILTERED;
4083 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4084 return; // event was consumed by the filter
4085 }
4086
4087 mLock.lock();
4088 }
4089
4090 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004091 std::unique_ptr<MotionEntry> newEntry =
4092 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4093 args->source, args->displayId, policyFlags,
4094 args->action, args->actionButton, args->flags,
4095 args->metaState, args->buttonState,
4096 args->classification, args->edgeFlags,
4097 args->xPrecision, args->yPrecision,
4098 args->xCursorPosition, args->yCursorPosition,
4099 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004100 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004102 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4103 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4104 !mInputFilterEnabled) {
4105 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4106 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4107 }
4108
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004109 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 mLock.unlock();
4111 } // release lock
4112
4113 if (needWake) {
4114 mLooper->wake();
4115 }
4116}
4117
Chris Yef59a2f42020-10-16 12:55:26 -07004118void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004119 if (DEBUG_INBOUND_EVENT_DETAILS) {
4120 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4121 " sensorType=%s",
4122 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004123 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004124 }
Chris Yef59a2f42020-10-16 12:55:26 -07004125
Antonio Kantekf16f2832021-09-28 04:39:20 +00004126 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004127 { // acquire lock
4128 mLock.lock();
4129
4130 // Just enqueue a new sensor event.
4131 std::unique_ptr<SensorEntry> newEntry =
4132 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4133 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4134 args->sensorType, args->accuracy,
4135 args->accuracyChanged, args->values);
4136
4137 needWake = enqueueInboundEventLocked(std::move(newEntry));
4138 mLock.unlock();
4139 } // release lock
4140
4141 if (needWake) {
4142 mLooper->wake();
4143 }
4144}
4145
Chris Yefb552902021-02-03 17:18:37 -08004146void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004147 if (DEBUG_INBOUND_EVENT_DETAILS) {
4148 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4149 args->deviceId, args->isOn);
4150 }
Chris Yefb552902021-02-03 17:18:37 -08004151 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4152}
4153
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004155 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156}
4157
4158void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004159 if (DEBUG_INBOUND_EVENT_DETAILS) {
4160 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4161 "switchMask=0x%08x",
4162 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
4165 uint32_t policyFlags = args->policyFlags;
4166 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168}
4169
4170void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004171 if (DEBUG_INBOUND_EVENT_DETAILS) {
4172 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4173 args->deviceId);
4174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175
Antonio Kantekf16f2832021-09-28 04:39:20 +00004176 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004178 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004180 std::unique_ptr<DeviceResetEntry> newEntry =
4181 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4182 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 } // release lock
4184
4185 if (needWake) {
4186 mLooper->wake();
4187 }
4188}
4189
Prabir Pradhan7e186182020-11-10 13:56:45 -08004190void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004191 if (DEBUG_INBOUND_EVENT_DETAILS) {
4192 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004193 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004194 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004195
Antonio Kantekf16f2832021-09-28 04:39:20 +00004196 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004197 { // acquire lock
4198 std::scoped_lock _l(mLock);
4199 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004200 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004201 needWake = enqueueInboundEventLocked(std::move(entry));
4202 } // release lock
4203
4204 if (needWake) {
4205 mLooper->wake();
4206 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004207}
4208
Prabir Pradhan5735a322022-04-11 17:23:34 +00004209InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4210 std::optional<int32_t> targetUid,
4211 InputEventInjectionSync syncMode,
4212 std::chrono::milliseconds timeout,
4213 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004214 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004215 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4216 "policyFlags=0x%08x",
4217 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4218 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004219 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004220 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221
Prabir Pradhan5735a322022-04-11 17:23:34 +00004222 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004225 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4226 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4227 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4228 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4229 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004231 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004232 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004233 }
4234
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004235 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004238 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4239 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004241 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004244 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004245 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4246 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4247 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004248 int32_t keyCode = incomingKey.getKeyCode();
4249 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004250 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004252 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004253 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004254 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4255 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4256 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4259 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004260 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261
4262 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4263 android::base::Timer t;
4264 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4265 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4266 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4267 std::to_string(t.duration().count()).c_str());
4268 }
4269 }
4270
4271 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004272 std::unique_ptr<KeyEntry> injectedEntry =
4273 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004274 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004275 incomingKey.getDisplayId(), policyFlags, action,
4276 flags, keyCode, incomingKey.getScanCode(), metaState,
4277 incomingKey.getRepeatCount(),
4278 incomingKey.getDownTime());
4279 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 }
4282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004285 const int32_t action = motionEvent.getAction();
4286 const bool isPointerEvent =
4287 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4288 // If a pointer event has no displayId specified, inject it to the default display.
4289 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4290 ? ADISPLAY_ID_DEFAULT
4291 : event->getDisplayId();
4292 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004293 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004294 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004295 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004297 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004298 }
4299
4300 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004301 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004302 android::base::Timer t;
4303 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4304 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4305 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4306 std::to_string(t.duration().count()).c_str());
4307 }
4308 }
4309
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004310 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4311 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4312 }
4313
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004315 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4316 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004317 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004318 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4319 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004320 displayId, policyFlags, action, actionButton,
4321 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004322 motionEvent.getButtonState(),
4323 motionEvent.getClassification(),
4324 motionEvent.getEdgeFlags(),
4325 motionEvent.getXPrecision(),
4326 motionEvent.getYPrecision(),
4327 motionEvent.getRawXCursorPosition(),
4328 motionEvent.getRawYCursorPosition(),
4329 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004330 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004331 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004332 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004333 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004334 sampleEventTimes += 1;
4335 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004336 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004337 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4338 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004339 displayId, policyFlags, action, actionButton,
4340 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004341 motionEvent.getButtonState(),
4342 motionEvent.getClassification(),
4343 motionEvent.getEdgeFlags(),
4344 motionEvent.getXPrecision(),
4345 motionEvent.getYPrecision(),
4346 motionEvent.getRawXCursorPosition(),
4347 motionEvent.getRawYCursorPosition(),
4348 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004349 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004350 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004351 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4352 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004353 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004354 }
4355 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004358 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004359 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004360 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 }
4362
Prabir Pradhan5735a322022-04-11 17:23:34 +00004363 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 injectionState->injectionIsAsync = true;
4366 }
4367
4368 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004369 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370
4371 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004372 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004373 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004374 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 }
4376
4377 mLock.unlock();
4378
4379 if (needWake) {
4380 mLooper->wake();
4381 }
4382
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004383 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004385 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 if (syncMode == InputEventInjectionSync::NONE) {
4388 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 } else {
4390 for (;;) {
4391 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004392 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 break;
4394 }
4395
4396 nsecs_t remainingTimeout = endTime - now();
4397 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004398 if (DEBUG_INJECTION) {
4399 ALOGD("injectInputEvent - Timed out waiting for injection result "
4400 "to become available.");
4401 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 break;
4404 }
4405
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004406 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 }
4408
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004409 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4410 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004412 if (DEBUG_INJECTION) {
4413 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4414 injectionState->pendingForegroundDispatches);
4415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 nsecs_t remainingTimeout = endTime - now();
4417 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004418 if (DEBUG_INJECTION) {
4419 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4420 "dispatches to finish.");
4421 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004422 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 break;
4424 }
4425
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004426 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 }
4428 }
4429 }
4430
4431 injectionState->release();
4432 } // release lock
4433
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004434 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004435 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
4438 return injectionResult;
4439}
4440
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004441std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004442 std::array<uint8_t, 32> calculatedHmac;
4443 std::unique_ptr<VerifiedInputEvent> result;
4444 switch (event.getType()) {
4445 case AINPUT_EVENT_TYPE_KEY: {
4446 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4447 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4448 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004449 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004450 break;
4451 }
4452 case AINPUT_EVENT_TYPE_MOTION: {
4453 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4454 VerifiedMotionEvent verifiedMotionEvent =
4455 verifiedMotionEventFromMotionEvent(motionEvent);
4456 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004457 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004458 break;
4459 }
4460 default: {
4461 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4462 return nullptr;
4463 }
4464 }
4465 if (calculatedHmac == INVALID_HMAC) {
4466 return nullptr;
4467 }
4468 if (calculatedHmac != event.getHmac()) {
4469 return nullptr;
4470 }
4471 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004472}
4473
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004474void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004475 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004476 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004478 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004479 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004482 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 // Log the outcome since the injector did not wait for the injection result.
4484 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004486 ALOGV("Asynchronous input event injection succeeded.");
4487 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004488 case InputEventInjectionResult::TARGET_MISMATCH:
4489 ALOGV("Asynchronous input event injection target mismatch.");
4490 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004491 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004492 ALOGW("Asynchronous input event injection failed.");
4493 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004494 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495 ALOGW("Asynchronous input event injection timed out.");
4496 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004497 case InputEventInjectionResult::PENDING:
4498 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4499 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 }
4501 }
4502
4503 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004504 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 }
4506}
4507
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004508void InputDispatcher::transformMotionEntryForInjectionLocked(
4509 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004510 // Input injection works in the logical display coordinate space, but the input pipeline works
4511 // display space, so we need to transform the injected events accordingly.
4512 const auto it = mDisplayInfos.find(entry.displayId);
4513 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004514 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004515
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004516 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4517 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4518 const vec2 cursor =
4519 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4520 {entry.xCursorPosition, entry.yCursorPosition});
4521 entry.xCursorPosition = cursor.x;
4522 entry.yCursorPosition = cursor.y;
4523 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004524 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004525 entry.pointerCoords[i] =
4526 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4527 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004528 }
4529}
4530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004531void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4532 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 if (injectionState) {
4534 injectionState->pendingForegroundDispatches += 1;
4535 }
4536}
4537
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004538void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4539 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 if (injectionState) {
4541 injectionState->pendingForegroundDispatches -= 1;
4542
4543 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004544 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 }
4546 }
4547}
4548
chaviw98318de2021-05-19 16:45:23 -05004549const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004550 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004551 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004552 auto it = mWindowHandlesByDisplay.find(displayId);
4553 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004554}
4555
chaviw98318de2021-05-19 16:45:23 -05004556sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004557 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004558 if (windowHandleToken == nullptr) {
4559 return nullptr;
4560 }
4561
Arthur Hungb92218b2018-08-14 12:00:21 +08004562 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004563 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4564 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004565 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004566 return windowHandle;
4567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 }
4569 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004570 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571}
4572
chaviw98318de2021-05-19 16:45:23 -05004573sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4574 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004575 if (windowHandleToken == nullptr) {
4576 return nullptr;
4577 }
4578
chaviw98318de2021-05-19 16:45:23 -05004579 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004580 if (windowHandle->getToken() == windowHandleToken) {
4581 return windowHandle;
4582 }
4583 }
4584 return nullptr;
4585}
4586
chaviw98318de2021-05-19 16:45:23 -05004587sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4588 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004589 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004590 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4591 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004592 if (handle->getId() == windowHandle->getId() &&
4593 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004594 if (windowHandle->getInfo()->displayId != it.first) {
4595 ALOGE("Found window %s in display %" PRId32
4596 ", but it should belong to display %" PRId32,
4597 windowHandle->getName().c_str(), it.first,
4598 windowHandle->getInfo()->displayId);
4599 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004600 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 }
4603 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004604 return nullptr;
4605}
4606
chaviw98318de2021-05-19 16:45:23 -05004607sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004608 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4609 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610}
4611
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004612bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4613 const MotionEntry& motionEntry) const {
4614 const WindowInfo& info = *window->getInfo();
4615
4616 // Skip spy window targets that are not valid for targeted injection.
4617 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004618 return false;
4619 }
4620
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004621 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4622 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4623 return false;
4624 }
4625
4626 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4627 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4628 window->getName().c_str());
4629 return false;
4630 }
4631
4632 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004633 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004634 ALOGW("Not sending touch to %s because there's no corresponding connection",
4635 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004636 return false;
4637 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004638
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004639 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004640 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004641 return false;
4642 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004643
4644 // Drop events that can't be trusted due to occlusion
4645 const auto [x, y] = resolveTouchedPosition(motionEntry);
4646 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4647 if (!isTouchTrustedLocked(occlusionInfo)) {
4648 if (DEBUG_TOUCH_OCCLUSION) {
4649 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4650 for (const auto& log : occlusionInfo.debugInfo) {
4651 ALOGD("%s", log.c_str());
4652 }
4653 }
4654 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4655 occlusionInfo.obscuringUid);
4656 return false;
4657 }
4658
4659 // Drop touch events if requested by input feature
4660 if (shouldDropInput(motionEntry, window)) {
4661 return false;
4662 }
4663
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004664 return true;
4665}
4666
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004667std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4668 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004669 auto connectionIt = mConnectionsByToken.find(token);
4670 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004671 return nullptr;
4672 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004673 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004674}
4675
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004676void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004677 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4678 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004679 // Remove all handles on a display if there are no windows left.
4680 mWindowHandlesByDisplay.erase(displayId);
4681 return;
4682 }
4683
4684 // Since we compare the pointer of input window handles across window updates, we need
4685 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004686 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4687 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4688 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004689 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004690 }
4691
chaviw98318de2021-05-19 16:45:23 -05004692 std::vector<sp<WindowInfoHandle>> newHandles;
4693 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004694 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004695 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004696 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004697 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004698 const bool canReceiveInput =
4699 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4700 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004701 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004702 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004703 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004704 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004705 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004706 }
4707
4708 if (info->displayId != displayId) {
4709 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4710 handle->getName().c_str(), displayId, info->displayId);
4711 continue;
4712 }
4713
Robert Carredd13602020-04-13 17:24:34 -07004714 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4715 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004716 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004717 oldHandle->updateFrom(handle);
4718 newHandles.push_back(oldHandle);
4719 } else {
4720 newHandles.push_back(handle);
4721 }
4722 }
4723
4724 // Insert or replace
4725 mWindowHandlesByDisplay[displayId] = newHandles;
4726}
4727
Arthur Hung72d8dc32020-03-28 00:48:39 +00004728void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004729 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004730 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004731 { // acquire lock
4732 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004733 for (const auto& [displayId, handles] : handlesPerDisplay) {
4734 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004735 }
4736 }
4737 // Wake up poll loop since it may need to make new input dispatching choices.
4738 mLooper->wake();
4739}
4740
Arthur Hungb92218b2018-08-14 12:00:21 +08004741/**
4742 * Called from InputManagerService, update window handle list by displayId that can receive input.
4743 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4744 * If set an empty list, remove all handles from the specific display.
4745 * For focused handle, check if need to change and send a cancel event to previous one.
4746 * For removed handle, check if need to send a cancel event if already in touch.
4747 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004748void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004749 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004750 if (DEBUG_FOCUS) {
4751 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004752 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004753 windowList += iwh->getName() + " ";
4754 }
4755 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757
Prabir Pradhand65552b2021-10-07 11:23:50 -07004758 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004759 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004760 const WindowInfo& info = *window->getInfo();
4761
4762 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004763 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004764 if (noInputWindow && window->getToken() != nullptr) {
4765 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4766 window->getName().c_str());
4767 window->releaseChannel();
4768 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004769
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004770 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004771 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4772 !info.inputConfig.test(
4773 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004774 "%s has feature SPY, but is not a trusted overlay.",
4775 window->getName().c_str());
4776
Prabir Pradhand65552b2021-10-07 11:23:50 -07004777 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004778 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4779 !info.inputConfig.test(
4780 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004781 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4782 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004783 }
4784
Arthur Hung72d8dc32020-03-28 00:48:39 +00004785 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004786 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004788 // Save the old windows' orientation by ID before it gets updated.
4789 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004790 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004791 oldWindowOrientations.emplace(handle->getId(),
4792 handle->getInfo()->transform.getOrientation());
4793 }
4794
chaviw98318de2021-05-19 16:45:23 -05004795 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004796
chaviw98318de2021-05-19 16:45:23 -05004797 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004798 if (mLastHoverWindowHandle &&
4799 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4800 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004801 mLastHoverWindowHandle = nullptr;
4802 }
4803
Vishnu Nairc519ff72021-01-21 08:23:08 -08004804 std::optional<FocusResolver::FocusChanges> changes =
4805 mFocusResolver.setInputWindows(displayId, windowHandles);
4806 if (changes) {
4807 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004810 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4811 mTouchStatesByDisplay.find(displayId);
4812 if (stateIt != mTouchStatesByDisplay.end()) {
4813 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004814 for (size_t i = 0; i < state.windows.size();) {
4815 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004816 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004817 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004818 ALOGD("Touched window was removed: %s in display %" PRId32,
4819 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004820 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004821 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004822 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4823 if (touchedInputChannel != nullptr) {
4824 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4825 "touched window was removed");
4826 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004827 // Since we are about to drop the touch, cancel the events for the wallpaper as
4828 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004829 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004830 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4831 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004832 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4833 if (wallpaper != nullptr) {
4834 sp<Connection> wallpaperConnection =
4835 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004836 if (wallpaperConnection != nullptr) {
4837 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4838 options);
4839 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004840 }
4841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004843 state.windows.erase(state.windows.begin() + i);
4844 } else {
4845 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 }
4847 }
arthurhungb89ccb02020-12-30 16:19:01 +08004848
arthurhung6d4bed92021-03-17 11:59:33 +08004849 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004850 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004851 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004852 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004853 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004854 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4855 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004856 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004857 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004858 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004859
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004860 // Determine if the orientation of any of the input windows have changed, and cancel all
4861 // pointer events if necessary.
4862 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4863 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4864 if (newWindowHandle != nullptr &&
4865 newWindowHandle->getInfo()->transform.getOrientation() !=
4866 oldWindowOrientations[oldWindowHandle->getId()]) {
4867 std::shared_ptr<InputChannel> inputChannel =
4868 getInputChannelLocked(newWindowHandle->getToken());
4869 if (inputChannel != nullptr) {
4870 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4871 "touched window's orientation changed");
4872 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004873 }
4874 }
4875 }
4876
Arthur Hung72d8dc32020-03-28 00:48:39 +00004877 // Release information for windows that are no longer present.
4878 // This ensures that unused input channels are released promptly.
4879 // Otherwise, they might stick around until the window handle is destroyed
4880 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004881 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004882 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004883 if (DEBUG_FOCUS) {
4884 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004885 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004886 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004887 }
chaviw291d88a2019-02-14 10:33:58 -08004888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889}
4890
4891void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004892 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004893 if (DEBUG_FOCUS) {
4894 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4895 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4896 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004897 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004898 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004899 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 } // release lock
4901
4902 // Wake up poll loop since it may need to make new input dispatching choices.
4903 mLooper->wake();
4904}
4905
Vishnu Nair599f1412021-06-21 10:39:58 -07004906void InputDispatcher::setFocusedApplicationLocked(
4907 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4908 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4909 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4910
4911 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4912 return; // This application is already focused. No need to wake up or change anything.
4913 }
4914
4915 // Set the new application handle.
4916 if (inputApplicationHandle != nullptr) {
4917 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4918 } else {
4919 mFocusedApplicationHandlesByDisplay.erase(displayId);
4920 }
4921
4922 // No matter what the old focused application was, stop waiting on it because it is
4923 // no longer focused.
4924 resetNoFocusedWindowTimeoutLocked();
4925}
4926
Tiger Huang721e26f2018-07-24 22:26:19 +08004927/**
4928 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4929 * the display not specified.
4930 *
4931 * We track any unreleased events for each window. If a window loses the ability to receive the
4932 * released event, we will send a cancel event to it. So when the focused display is changed, we
4933 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4934 * display. The display-specified events won't be affected.
4935 */
4936void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004937 if (DEBUG_FOCUS) {
4938 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4939 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004940 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004941 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004942
4943 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004944 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004945 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004946 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004947 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004948 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004949 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004950 CancelationOptions
4951 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4952 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004953 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004954 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4955 }
4956 }
4957 mFocusedDisplayId = displayId;
4958
Chris Ye3c2d6f52020-08-09 10:39:48 -07004959 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004960 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004961 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004962
Vishnu Nairad321cd2020-08-20 16:40:21 -07004963 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004964 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004965 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004966 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004967 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004968 }
4969 }
4970 }
4971
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004972 if (DEBUG_FOCUS) {
4973 logDispatchStateLocked();
4974 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004975 } // release lock
4976
4977 // Wake up poll loop since it may need to make new input dispatching choices.
4978 mLooper->wake();
4979}
4980
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004982 if (DEBUG_FOCUS) {
4983 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985
4986 bool changed;
4987 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004988 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989
4990 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4991 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004992 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993 }
4994
4995 if (mDispatchEnabled && !enabled) {
4996 resetAndDropEverythingLocked("dispatcher is being disabled");
4997 }
4998
4999 mDispatchEnabled = enabled;
5000 mDispatchFrozen = frozen;
5001 changed = true;
5002 } else {
5003 changed = false;
5004 }
5005
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005006 if (DEBUG_FOCUS) {
5007 logDispatchStateLocked();
5008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 } // release lock
5010
5011 if (changed) {
5012 // Wake up poll loop since it may need to make new input dispatching choices.
5013 mLooper->wake();
5014 }
5015}
5016
5017void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005018 if (DEBUG_FOCUS) {
5019 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021
5022 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005023 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024
5025 if (mInputFilterEnabled == enabled) {
5026 return;
5027 }
5028
5029 mInputFilterEnabled = enabled;
5030 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5031 } // release lock
5032
5033 // Wake up poll loop since there might be work to do to drop everything.
5034 mLooper->wake();
5035}
5036
Antonio Kanteka042c022022-07-06 16:51:07 -07005037bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5038 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005039 bool needWake = false;
5040 {
5041 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005042 ALOGD_IF(DEBUG_TOUCH_MODE,
5043 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5044 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5045 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5046 mTouchModePerDisplay.count(displayId) == 0
5047 ? "not set"
5048 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5049
Antonio Kantek15beb512022-06-13 22:35:41 +00005050 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5051 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005052 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005053 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005054 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005055 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5056 !recentWindowsAreOwnedByLocked(pid, uid)) {
5057 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5058 "window nor none of the previously interacted window",
5059 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005060 return false;
5061 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005062 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005063 mTouchModePerDisplay[displayId] = inTouchMode;
5064 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5065 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005066 needWake = enqueueInboundEventLocked(std::move(entry));
5067 } // release lock
5068
5069 if (needWake) {
5070 mLooper->wake();
5071 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005072 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005073}
5074
Antonio Kantek48710e42022-03-24 14:19:30 -07005075bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5076 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5077 if (focusedToken == nullptr) {
5078 return false;
5079 }
5080 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5081 return isWindowOwnedBy(windowHandle, pid, uid);
5082}
5083
5084bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5085 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5086 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5087 const sp<WindowInfoHandle> windowHandle =
5088 getWindowHandleLocked(connectionToken);
5089 return isWindowOwnedBy(windowHandle, pid, uid);
5090 }) != mInteractionConnectionTokens.end();
5091}
5092
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005093void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5094 if (opacity < 0 || opacity > 1) {
5095 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5096 return;
5097 }
5098
5099 std::scoped_lock lock(mLock);
5100 mMaximumObscuringOpacityForTouch = opacity;
5101}
5102
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005103std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5104InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005105 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5106 for (TouchedWindow& w : state.windows) {
5107 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005108 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005109 }
5110 }
5111 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005112 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005113}
5114
arthurhungb89ccb02020-12-30 16:19:01 +08005115bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5116 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005117 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005118 if (DEBUG_FOCUS) {
5119 ALOGD("Trivial transfer to same window.");
5120 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005121 return true;
5122 }
5123
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005125 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126
Arthur Hungabbb9d82021-09-01 14:52:30 +00005127 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005128 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005129 if (state == nullptr || touchedWindow == nullptr) {
5130 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 return false;
5132 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005133
Arthur Hungabbb9d82021-09-01 14:52:30 +00005134 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5135 if (toWindowHandle == nullptr) {
5136 ALOGW("Cannot transfer focus because to window not found.");
5137 return false;
5138 }
5139
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005140 if (DEBUG_FOCUS) {
5141 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005142 touchedWindow->windowHandle->getName().c_str(),
5143 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 }
5145
Arthur Hungabbb9d82021-09-01 14:52:30 +00005146 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005147 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005148 BitSet32 pointerIds = touchedWindow->pointerIds;
5149 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150
Arthur Hungabbb9d82021-09-01 14:52:30 +00005151 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005152 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005153 ftl::Flags<InputTarget::Flags> newTargetFlags =
5154 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005155 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005156 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005157 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005158 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159
Arthur Hungabbb9d82021-09-01 14:52:30 +00005160 // Store the dragging window.
5161 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005162 if (pointerIds.count() != 1) {
5163 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5164 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005165 return false;
5166 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005167 // Track the pointer id for drag window and generate the drag state.
5168 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005169 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
5171
Arthur Hungabbb9d82021-09-01 14:52:30 +00005172 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005173 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5174 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005175 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005176 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005177 CancelationOptions
5178 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5179 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005181 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 }
5183
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005184 if (DEBUG_FOCUS) {
5185 logDispatchStateLocked();
5186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 } // release lock
5188
5189 // Wake up poll loop since it may need to make new input dispatching choices.
5190 mLooper->wake();
5191 return true;
5192}
5193
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005194/**
5195 * Get the touched foreground window on the given display.
5196 * Return null if there are no windows touched on that display, or if more than one foreground
5197 * window is being touched.
5198 */
5199sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5200 auto stateIt = mTouchStatesByDisplay.find(displayId);
5201 if (stateIt == mTouchStatesByDisplay.end()) {
5202 ALOGI("No touch state on display %" PRId32, displayId);
5203 return nullptr;
5204 }
5205
5206 const TouchState& state = stateIt->second;
5207 sp<WindowInfoHandle> touchedForegroundWindow;
5208 // If multiple foreground windows are touched, return nullptr
5209 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005210 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005211 if (touchedForegroundWindow != nullptr) {
5212 ALOGI("Two or more foreground windows: %s and %s",
5213 touchedForegroundWindow->getName().c_str(),
5214 window.windowHandle->getName().c_str());
5215 return nullptr;
5216 }
5217 touchedForegroundWindow = window.windowHandle;
5218 }
5219 }
5220 return touchedForegroundWindow;
5221}
5222
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005223// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005224bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005225 sp<IBinder> fromToken;
5226 { // acquire lock
5227 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005228 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005229 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005230 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5231 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005232 return false;
5233 }
5234
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005235 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5236 if (from == nullptr) {
5237 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5238 return false;
5239 }
5240
5241 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005242 } // release lock
5243
5244 return transferTouchFocus(fromToken, destChannelToken);
5245}
5246
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005248 if (DEBUG_FOCUS) {
5249 ALOGD("Resetting and dropping all events (%s).", reason);
5250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251
5252 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5253 synthesizeCancelationEventsForAllConnectionsLocked(options);
5254
5255 resetKeyRepeatLocked();
5256 releasePendingEventLocked();
5257 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005258 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005260 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005261 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005263 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264}
5265
5266void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005267 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 dumpDispatchStateLocked(dump);
5269
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005270 std::istringstream stream(dump);
5271 std::string line;
5272
5273 while (std::getline(stream, line, '\n')) {
5274 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275 }
5276}
5277
Prabir Pradhan99987712020-11-10 18:43:05 -08005278std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5279 std::string dump;
5280
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005281 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5282 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005283
5284 std::string windowName = "None";
5285 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005286 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005287 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5288 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5289 : "token has capture without window";
5290 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005291 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005292
5293 return dump;
5294}
5295
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005296void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005297 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5298 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5299 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005300 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301
Tiger Huang721e26f2018-07-24 22:26:19 +08005302 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5303 dump += StringPrintf(INDENT "FocusedApplications:\n");
5304 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5305 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005306 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005307 const std::chrono::duration timeout =
5308 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005309 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005310 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005311 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005314 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005316
Vishnu Nairc519ff72021-01-21 08:23:08 -08005317 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005318 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005320 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005321 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005322 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005323 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5324 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 }
5326 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005327 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 }
5329
arthurhung6d4bed92021-03-17 11:59:33 +08005330 if (mDragState) {
5331 dump += StringPrintf(INDENT "DragState:\n");
5332 mDragState->dump(dump, INDENT2);
5333 }
5334
Arthur Hungb92218b2018-08-14 12:00:21 +08005335 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005336 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5337 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5338 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5339 const auto& displayInfo = it->second;
5340 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5341 displayInfo.logicalHeight);
5342 displayInfo.transform.dump(dump, "transform", INDENT4);
5343 } else {
5344 dump += INDENT2 "No DisplayInfo found!\n";
5345 }
5346
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005347 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005348 dump += INDENT2 "Windows:\n";
5349 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005350 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5351 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005353 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005354 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005355 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005356 "applicationInfo.name=%s, "
5357 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005358 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005359 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005360 windowInfo->displayId,
5361 windowInfo->inputConfig.string().c_str(),
5362 windowInfo->alpha, windowInfo->frameLeft,
5363 windowInfo->frameTop, windowInfo->frameRight,
5364 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005365 windowInfo->applicationInfo.name.c_str(),
5366 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005367 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005368 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005369 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005370 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005371 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005372 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005373 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005374 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005375 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005376 }
5377 } else {
5378 dump += INDENT2 "Windows: <none>\n";
5379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 }
5381 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005382 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005383 }
5384
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005385 if (!mGlobalMonitorsByDisplay.empty()) {
5386 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5387 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005388 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005391 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392 }
5393
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005394 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395
5396 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005397 if (!mRecentQueue.empty()) {
5398 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005399 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005400 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005401 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005402 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 }
5404 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005405 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 }
5407
5408 // Dump event currently being dispatched.
5409 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005410 dump += INDENT "PendingEvent:\n";
5411 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005412 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005413 dump += StringPrintf(", age=%" PRId64 "ms\n",
5414 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005415 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005416 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417 }
5418
5419 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005420 if (!mInboundQueue.empty()) {
5421 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005422 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005423 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005424 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005425 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 }
5427 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005428 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005431 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005432 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005433 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5434 const KeyReplacement& replacement = pair.first;
5435 int32_t newKeyCode = pair.second;
5436 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005437 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005438 }
5439 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005440 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005441 }
5442
Prabir Pradhancef936d2021-07-21 16:17:52 +00005443 if (!mCommandQueue.empty()) {
5444 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5445 } else {
5446 dump += INDENT "CommandQueue: <empty>\n";
5447 }
5448
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005449 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005450 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005451 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005452 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005453 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005454 connection->inputChannel->getFd().get(),
5455 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005456 connection->getWindowName().c_str(),
5457 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005458 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005460 if (!connection->outboundQueue.empty()) {
5461 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5462 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005463 dump += dumpQueue(connection->outboundQueue, currentTime);
5464
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005466 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 }
5468
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005469 if (!connection->waitQueue.empty()) {
5470 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5471 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005472 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005474 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 }
5476 }
5477 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005478 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 }
5480
5481 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005482 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5483 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005485 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 }
5487
Antonio Kantek15beb512022-06-13 22:35:41 +00005488 if (!mTouchModePerDisplay.empty()) {
5489 dump += INDENT "TouchModePerDisplay:\n";
5490 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5491 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5492 std::to_string(touchMode).c_str());
5493 }
5494 } else {
5495 dump += INDENT "TouchModePerDisplay: <none>\n";
5496 }
5497
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005498 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005499 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5500 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5501 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005502 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005503 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005504}
5505
Michael Wright3dd60e22019-03-27 22:06:44 +00005506void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5507 const size_t numMonitors = monitors.size();
5508 for (size_t i = 0; i < numMonitors; i++) {
5509 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005510 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005511 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5512 dump += "\n";
5513 }
5514}
5515
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005516class LooperEventCallback : public LooperCallback {
5517public:
5518 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5519 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5520
5521private:
5522 std::function<int(int events)> mCallback;
5523};
5524
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005525Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005526 if (DEBUG_CHANNEL_CREATION) {
5527 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005530 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005531 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005532 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005533
5534 if (result) {
5535 return base::Error(result) << "Failed to open input channel pair with name " << name;
5536 }
5537
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005539 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005540 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005541 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005542 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005543 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005545 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5546 ALOGE("Created a new connection, but the token %p is already known", token.get());
5547 }
5548 mConnectionsByToken.emplace(token, connection);
5549
5550 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5551 this, std::placeholders::_1, token);
5552
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005553 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5554 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 } // release lock
5556
5557 // Wake the looper because some connections have changed.
5558 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005559 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560}
5561
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005562Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005563 const std::string& name,
5564 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005565 std::shared_ptr<InputChannel> serverChannel;
5566 std::unique_ptr<InputChannel> clientChannel;
5567 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5568 if (result) {
5569 return base::Error(result) << "Failed to open input channel pair with name " << name;
5570 }
5571
Michael Wright3dd60e22019-03-27 22:06:44 +00005572 { // acquire lock
5573 std::scoped_lock _l(mLock);
5574
5575 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005576 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5577 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005578 }
5579
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005580 sp<Connection> connection =
5581 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005582 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005583 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005584
5585 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5586 ALOGE("Created a new connection, but the token %p is already known", token.get());
5587 }
5588 mConnectionsByToken.emplace(token, connection);
5589 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5590 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005591
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005592 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005593
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005594 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5595 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005596 }
Garfield Tan15601662020-09-22 15:32:38 -07005597
Michael Wright3dd60e22019-03-27 22:06:44 +00005598 // Wake the looper because some connections have changed.
5599 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005600 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005601}
5602
Garfield Tan15601662020-09-22 15:32:38 -07005603status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005605 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606
Garfield Tan15601662020-09-22 15:32:38 -07005607 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608 if (status) {
5609 return status;
5610 }
5611 } // release lock
5612
5613 // Wake the poll loop because removing the connection may have changed the current
5614 // synchronization state.
5615 mLooper->wake();
5616 return OK;
5617}
5618
Garfield Tan15601662020-09-22 15:32:38 -07005619status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5620 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005621 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005622 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005623 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 return BAD_VALUE;
5625 }
5626
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005627 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005628
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005630 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 }
5632
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005633 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634
5635 nsecs_t currentTime = now();
5636 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5637
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005638 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 return OK;
5640}
5641
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005642void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005643 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5644 auto& [displayId, monitors] = *it;
5645 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5646 return monitor.inputChannel->getConnectionToken() == connectionToken;
5647 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005648
Michael Wright3dd60e22019-03-27 22:06:44 +00005649 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005650 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005651 } else {
5652 ++it;
5653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 }
5655}
5656
Michael Wright3dd60e22019-03-27 22:06:44 +00005657status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005658 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005659 return pilferPointersLocked(token);
5660}
Michael Wright3dd60e22019-03-27 22:06:44 +00005661
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005662status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005663 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5664 if (!requestingChannel) {
5665 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5666 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005667 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005668
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005669 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005670 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005671 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5672 " Ignoring.");
5673 return BAD_VALUE;
5674 }
5675
5676 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005677 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005678 // Send cancel events to all the input channels we're stealing from.
5679 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5680 "input channel stole pointer stream");
5681 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005682 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005683 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005684 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005685 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005686 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005687 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005688 if (channel != nullptr && channel->getConnectionToken() != token) {
5689 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5690 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5691 canceledWindows += channel->getName();
5692 }
5693 }
5694 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5695 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5696 canceledWindows.c_str());
5697
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005698 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005699 // This only blocks relevant pointers to be sent to other windows
5700 window.isPilferingPointers = true;
5701
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005702 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005703 return OK;
5704}
5705
Prabir Pradhan99987712020-11-10 18:43:05 -08005706void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5707 { // acquire lock
5708 std::scoped_lock _l(mLock);
5709 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005710 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005711 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5712 windowHandle != nullptr ? windowHandle->getName().c_str()
5713 : "token without window");
5714 }
5715
Vishnu Nairc519ff72021-01-21 08:23:08 -08005716 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005717 if (focusedToken != windowToken) {
5718 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5719 enabled ? "enable" : "disable");
5720 return;
5721 }
5722
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005723 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005724 ALOGW("Ignoring request to %s Pointer Capture: "
5725 "window has %s requested pointer capture.",
5726 enabled ? "enable" : "disable", enabled ? "already" : "not");
5727 return;
5728 }
5729
Christine Franksb768bb42021-11-29 12:11:31 -08005730 if (enabled) {
5731 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5732 mIneligibleDisplaysForPointerCapture.end(),
5733 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5734 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5735 return;
5736 }
5737 }
5738
Prabir Pradhan99987712020-11-10 18:43:05 -08005739 setPointerCaptureLocked(enabled);
5740 } // release lock
5741
5742 // Wake the thread to process command entries.
5743 mLooper->wake();
5744}
5745
Christine Franksb768bb42021-11-29 12:11:31 -08005746void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5747 { // acquire lock
5748 std::scoped_lock _l(mLock);
5749 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5750 if (!isEligible) {
5751 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5752 }
5753 } // release lock
5754}
5755
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005756std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5757 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005758 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005759 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005760 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005761 }
5762 }
5763 }
5764 return std::nullopt;
5765}
5766
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005767sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005768 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005769 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005770 }
5771
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005772 for (const auto& [token, connection] : mConnectionsByToken) {
5773 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005774 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 }
5776 }
Robert Carr4e670e52018-08-15 13:26:12 -07005777
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005778 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779}
5780
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005781std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5782 sp<Connection> connection = getConnectionLocked(connectionToken);
5783 if (connection == nullptr) {
5784 return "<nullptr>";
5785 }
5786 return connection->getInputChannelName();
5787}
5788
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005789void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005790 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005791 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005792}
5793
Prabir Pradhancef936d2021-07-21 16:17:52 +00005794void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5795 const sp<Connection>& connection, uint32_t seq,
5796 bool handled, nsecs_t consumeTime) {
5797 // Handle post-event policy actions.
5798 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5799 if (dispatchEntryIt == connection->waitQueue.end()) {
5800 return;
5801 }
5802 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5803 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5804 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5805 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5806 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5807 }
5808 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5809 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5810 connection->inputChannel->getConnectionToken(),
5811 dispatchEntry->deliveryTime, consumeTime, finishTime);
5812 }
5813
5814 bool restartEvent;
5815 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5816 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5817 restartEvent =
5818 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5819 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5820 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5821 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5822 handled);
5823 } else {
5824 restartEvent = false;
5825 }
5826
5827 // Dequeue the event and start the next cycle.
5828 // Because the lock might have been released, it is possible that the
5829 // contents of the wait queue to have been drained, so we need to double-check
5830 // a few things.
5831 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5832 if (dispatchEntryIt != connection->waitQueue.end()) {
5833 dispatchEntry = *dispatchEntryIt;
5834 connection->waitQueue.erase(dispatchEntryIt);
5835 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5836 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5837 if (!connection->responsive) {
5838 connection->responsive = isConnectionResponsive(*connection);
5839 if (connection->responsive) {
5840 // The connection was unresponsive, and now it's responsive.
5841 processConnectionResponsiveLocked(*connection);
5842 }
5843 }
5844 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005845 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005846 connection->outboundQueue.push_front(dispatchEntry);
5847 traceOutboundQueueLength(*connection);
5848 } else {
5849 releaseDispatchEntry(dispatchEntry);
5850 }
5851 }
5852
5853 // Start the next dispatch cycle for this connection.
5854 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855}
5856
Prabir Pradhancef936d2021-07-21 16:17:52 +00005857void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5858 const sp<IBinder>& newToken) {
5859 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5860 scoped_unlock unlock(mLock);
5861 mPolicy->notifyFocusChanged(oldToken, newToken);
5862 };
5863 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864}
5865
Prabir Pradhancef936d2021-07-21 16:17:52 +00005866void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5867 auto command = [this, token, x, y]() REQUIRES(mLock) {
5868 scoped_unlock unlock(mLock);
5869 mPolicy->notifyDropWindow(token, x, y);
5870 };
5871 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005872}
5873
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005874void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5875 if (connection == nullptr) {
5876 LOG_ALWAYS_FATAL("Caller must check for nullness");
5877 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005878 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5879 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005880 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005881 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005882 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005883 return;
5884 }
5885 /**
5886 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5887 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5888 * has changed. This could cause newer entries to time out before the already dispatched
5889 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5890 * processes the events linearly. So providing information about the oldest entry seems to be
5891 * most useful.
5892 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005894 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5895 std::string reason =
5896 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005897 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898 ns2ms(currentWait),
5899 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005900 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005901 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005902
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005903 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5904
5905 // Stop waking up for events on this connection, it is already unresponsive
5906 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005907}
5908
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005909void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5910 std::string reason =
5911 StringPrintf("%s does not have a focused window", application->getName().c_str());
5912 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005913
Prabir Pradhancef936d2021-07-21 16:17:52 +00005914 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5915 scoped_unlock unlock(mLock);
5916 mPolicy->notifyNoFocusedWindowAnr(application);
5917 };
5918 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005919}
5920
chaviw98318de2021-05-19 16:45:23 -05005921void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005922 const std::string& reason) {
5923 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5924 updateLastAnrStateLocked(windowLabel, reason);
5925}
5926
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005927void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5928 const std::string& reason) {
5929 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005930 updateLastAnrStateLocked(windowLabel, reason);
5931}
5932
5933void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5934 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005936 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 struct tm tm;
5938 localtime_r(&t, &tm);
5939 char timestr[64];
5940 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005941 mLastAnrState.clear();
5942 mLastAnrState += INDENT "ANR:\n";
5943 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005944 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5945 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005946 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947}
5948
Prabir Pradhancef936d2021-07-21 16:17:52 +00005949void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5950 KeyEntry& entry) {
5951 const KeyEvent event = createKeyEvent(entry);
5952 nsecs_t delay = 0;
5953 { // release lock
5954 scoped_unlock unlock(mLock);
5955 android::base::Timer t;
5956 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5957 entry.policyFlags);
5958 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5959 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5960 std::to_string(t.duration().count()).c_str());
5961 }
5962 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963
5964 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005965 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005966 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005967 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005969 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5970 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972}
5973
Prabir Pradhancef936d2021-07-21 16:17:52 +00005974void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005975 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005976 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005977 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005978 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005979 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005980 };
5981 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005982}
5983
Prabir Pradhanedd96402022-02-15 01:46:16 -08005984void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5985 std::optional<int32_t> pid) {
5986 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005987 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005988 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005989 };
5990 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005991}
5992
5993/**
5994 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5995 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5996 * command entry to the command queue.
5997 */
5998void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5999 std::string reason) {
6000 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006001 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006002 if (connection.monitor) {
6003 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6004 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006005 pid = findMonitorPidByTokenLocked(connectionToken);
6006 } else {
6007 // The connection is a window
6008 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6009 reason.c_str());
6010 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6011 if (handle != nullptr) {
6012 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006013 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006014 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006015 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006016}
6017
6018/**
6019 * Tell the policy that a connection has become responsive so that it can stop ANR.
6020 */
6021void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6022 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006023 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006024 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006025 pid = findMonitorPidByTokenLocked(connectionToken);
6026 } else {
6027 // The connection is a window
6028 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6029 if (handle != nullptr) {
6030 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006031 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006032 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006033 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034}
6035
Prabir Pradhancef936d2021-07-21 16:17:52 +00006036bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006037 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006038 KeyEntry& keyEntry, bool handled) {
6039 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006040 if (!handled) {
6041 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006042 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006043 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044 return false;
6045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006047 // Get the fallback key state.
6048 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006049 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006050 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006051 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006052 connection->inputState.removeFallbackKey(originalKeyCode);
6053 }
6054
6055 if (handled || !dispatchEntry->hasForegroundTarget()) {
6056 // If the application handles the original key for which we previously
6057 // generated a fallback or if the window is not a foreground window,
6058 // then cancel the associated fallback key, if any.
6059 if (fallbackKeyCode != -1) {
6060 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006061 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6062 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6063 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6064 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6065 keyEntry.policyFlags);
6066 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006067 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006068 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069
6070 mLock.unlock();
6071
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006072 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006073 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074
6075 mLock.lock();
6076
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006077 // Cancel the fallback key.
6078 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006080 "application handled the original non-fallback key "
6081 "or is no longer a foreground target, "
6082 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 options.keyCode = fallbackKeyCode;
6084 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006085 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006086 connection->inputState.removeFallbackKey(originalKeyCode);
6087 }
6088 } else {
6089 // If the application did not handle a non-fallback key, first check
6090 // that we are in a good state to perform unhandled key event processing
6091 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006092 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006093 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006094 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6095 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6096 "since this is not an initial down. "
6097 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6098 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6099 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006100 return false;
6101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006103 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006104 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6105 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6106 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6107 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6108 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006109 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006110
6111 mLock.unlock();
6112
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006113 bool fallback =
6114 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006115 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006116
6117 mLock.lock();
6118
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006119 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120 connection->inputState.removeFallbackKey(originalKeyCode);
6121 return false;
6122 }
6123
6124 // Latch the fallback keycode for this key on an initial down.
6125 // The fallback keycode cannot change at any other point in the lifecycle.
6126 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006127 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006128 fallbackKeyCode = event.getKeyCode();
6129 } else {
6130 fallbackKeyCode = AKEYCODE_UNKNOWN;
6131 }
6132 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6133 }
6134
6135 ALOG_ASSERT(fallbackKeyCode != -1);
6136
6137 // Cancel the fallback key if the policy decides not to send it anymore.
6138 // We will continue to dispatch the key to the policy but we will no
6139 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006140 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6141 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006142 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6143 if (fallback) {
6144 ALOGD("Unhandled key event: Policy requested to send key %d"
6145 "as a fallback for %d, but on the DOWN it had requested "
6146 "to send %d instead. Fallback canceled.",
6147 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6148 } else {
6149 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6150 "but on the DOWN it had requested to send %d. "
6151 "Fallback canceled.",
6152 originalKeyCode, fallbackKeyCode);
6153 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006154 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006155
6156 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6157 "canceling fallback, policy no longer desires it");
6158 options.keyCode = fallbackKeyCode;
6159 synthesizeCancelationEventsForConnectionLocked(connection, options);
6160
6161 fallback = false;
6162 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006163 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006164 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006165 }
6166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006168 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6169 {
6170 std::string msg;
6171 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6172 connection->inputState.getFallbackKeys();
6173 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6174 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6175 }
6176 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6177 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006179 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006180
6181 if (fallback) {
6182 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006183 keyEntry.eventTime = event.getEventTime();
6184 keyEntry.deviceId = event.getDeviceId();
6185 keyEntry.source = event.getSource();
6186 keyEntry.displayId = event.getDisplayId();
6187 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6188 keyEntry.keyCode = fallbackKeyCode;
6189 keyEntry.scanCode = event.getScanCode();
6190 keyEntry.metaState = event.getMetaState();
6191 keyEntry.repeatCount = event.getRepeatCount();
6192 keyEntry.downTime = event.getDownTime();
6193 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006194
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006195 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6196 ALOGD("Unhandled key event: Dispatching fallback key. "
6197 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6198 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6199 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006200 return true; // restart the event
6201 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006202 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6203 ALOGD("Unhandled key event: No fallback key.");
6204 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006205
6206 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006207 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208 }
6209 }
6210 return false;
6211}
6212
Prabir Pradhancef936d2021-07-21 16:17:52 +00006213bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006214 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006215 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216 return false;
6217}
6218
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219void InputDispatcher::traceInboundQueueLengthLocked() {
6220 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006221 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 }
6223}
6224
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006225void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 if (ATRACE_ENABLED()) {
6227 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006228 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6229 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 }
6231}
6232
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006233void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 if (ATRACE_ENABLED()) {
6235 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006236 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6237 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 }
6239}
6240
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006241void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006242 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006243
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006244 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245 dumpDispatchStateLocked(dump);
6246
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006247 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006248 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006249 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250 }
6251}
6252
6253void InputDispatcher::monitor() {
6254 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006255 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006257 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258}
6259
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006260/**
6261 * Wake up the dispatcher and wait until it processes all events and commands.
6262 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6263 * this method can be safely called from any thread, as long as you've ensured that
6264 * the work you are interested in completing has already been queued.
6265 */
6266bool InputDispatcher::waitForIdle() {
6267 /**
6268 * Timeout should represent the longest possible time that a device might spend processing
6269 * events and commands.
6270 */
6271 constexpr std::chrono::duration TIMEOUT = 100ms;
6272 std::unique_lock lock(mLock);
6273 mLooper->wake();
6274 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6275 return result == std::cv_status::no_timeout;
6276}
6277
Vishnu Naire798b472020-07-23 13:52:21 -07006278/**
6279 * Sets focus to the window identified by the token. This must be called
6280 * after updating any input window handles.
6281 *
6282 * Params:
6283 * request.token - input channel token used to identify the window that should gain focus.
6284 * request.focusedToken - the token that the caller expects currently to be focused. If the
6285 * specified token does not match the currently focused window, this request will be dropped.
6286 * If the specified focused token matches the currently focused window, the call will succeed.
6287 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6288 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6289 * when requesting the focus change. This determines which request gets
6290 * precedence if there is a focus change request from another source such as pointer down.
6291 */
Vishnu Nair958da932020-08-21 17:12:37 -07006292void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6293 { // acquire lock
6294 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006295 std::optional<FocusResolver::FocusChanges> changes =
6296 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6297 if (changes) {
6298 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006299 }
6300 } // release lock
6301 // Wake up poll loop since it may need to make new input dispatching choices.
6302 mLooper->wake();
6303}
6304
Vishnu Nairc519ff72021-01-21 08:23:08 -08006305void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6306 if (changes.oldFocus) {
6307 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006308 if (focusedInputChannel) {
6309 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6310 "focus left window");
6311 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006312 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006313 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006314 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006315 if (changes.newFocus) {
6316 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006317 }
6318
Prabir Pradhan99987712020-11-10 18:43:05 -08006319 // If a window has pointer capture, then it must have focus. We need to ensure that this
6320 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6321 // If the window loses focus before it loses pointer capture, then the window can be in a state
6322 // where it has pointer capture but not focus, violating the contract. Therefore we must
6323 // dispatch the pointer capture event before the focus event. Since focus events are added to
6324 // the front of the queue (above), we add the pointer capture event to the front of the queue
6325 // after the focus events are added. This ensures the pointer capture event ends up at the
6326 // front.
6327 disablePointerCaptureForcedLocked();
6328
Vishnu Nairc519ff72021-01-21 08:23:08 -08006329 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006330 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006331 }
6332}
Vishnu Nair958da932020-08-21 17:12:37 -07006333
Prabir Pradhan99987712020-11-10 18:43:05 -08006334void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006335 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006336 return;
6337 }
6338
6339 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6340
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006341 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006342 setPointerCaptureLocked(false);
6343 }
6344
6345 if (!mWindowTokenWithPointerCapture) {
6346 // No need to send capture changes because no window has capture.
6347 return;
6348 }
6349
6350 if (mPendingEvent != nullptr) {
6351 // Move the pending event to the front of the queue. This will give the chance
6352 // for the pending event to be dropped if it is a captured event.
6353 mInboundQueue.push_front(mPendingEvent);
6354 mPendingEvent = nullptr;
6355 }
6356
6357 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006358 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006359 mInboundQueue.push_front(std::move(entry));
6360}
6361
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006362void InputDispatcher::setPointerCaptureLocked(bool enable) {
6363 mCurrentPointerCaptureRequest.enable = enable;
6364 mCurrentPointerCaptureRequest.seq++;
6365 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006366 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006367 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006368 };
6369 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006370}
6371
Vishnu Nair599f1412021-06-21 10:39:58 -07006372void InputDispatcher::displayRemoved(int32_t displayId) {
6373 { // acquire lock
6374 std::scoped_lock _l(mLock);
6375 // Set an empty list to remove all handles from the specific display.
6376 setInputWindowsLocked(/* window handles */ {}, displayId);
6377 setFocusedApplicationLocked(displayId, nullptr);
6378 // Call focus resolver to clean up stale requests. This must be called after input windows
6379 // have been removed for the removed display.
6380 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006381 // Reset pointer capture eligibility, regardless of previous state.
6382 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006383 // Remove the associated touch mode state.
6384 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006385 } // release lock
6386
6387 // Wake up poll loop since it may need to make new input dispatching choices.
6388 mLooper->wake();
6389}
6390
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006391void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6392 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006393 // The listener sends the windows as a flattened array. Separate the windows by display for
6394 // more convenient parsing.
6395 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006396 for (const auto& info : windowInfos) {
6397 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006398 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006399 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006400
6401 { // acquire lock
6402 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006403
6404 // Ensure that we have an entry created for all existing displays so that if a displayId has
6405 // no windows, we can tell that the windows were removed from the display.
6406 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6407 handlesPerDisplay[displayId];
6408 }
6409
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006410 mDisplayInfos.clear();
6411 for (const auto& displayInfo : displayInfos) {
6412 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6413 }
6414
6415 for (const auto& [displayId, handles] : handlesPerDisplay) {
6416 setInputWindowsLocked(handles, displayId);
6417 }
6418 }
6419 // Wake up poll loop since it may need to make new input dispatching choices.
6420 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006421}
6422
Vishnu Nair062a8672021-09-03 16:07:44 -07006423bool InputDispatcher::shouldDropInput(
6424 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006425 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6426 (windowHandle->getInfo()->inputConfig.test(
6427 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006428 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006429 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6430 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006431 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006432 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006433 windowHandle->getInfo()->displayId);
6434 return true;
6435 }
6436 return false;
6437}
6438
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006439void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6440 const std::vector<gui::WindowInfo>& windowInfos,
6441 const std::vector<DisplayInfo>& displayInfos) {
6442 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6443}
6444
Arthur Hungdfd528e2021-12-08 13:23:04 +00006445void InputDispatcher::cancelCurrentTouch() {
6446 {
6447 std::scoped_lock _l(mLock);
6448 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6449 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6450 "cancel current touch");
6451 synthesizeCancelationEventsForAllConnectionsLocked(options);
6452
6453 mTouchStatesByDisplay.clear();
6454 mLastHoverWindowHandle.clear();
6455 }
6456 // Wake up poll loop since there might be work to do.
6457 mLooper->wake();
6458}
6459
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006460void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6461 std::scoped_lock _l(mLock);
6462 mMonitorDispatchingTimeout = timeout;
6463}
6464
Garfield Tane84e6f92019-08-29 17:28:41 -07006465} // namespace android::inputdispatcher