blob: 01aa221b053a28f09cdf871674f9eeef69886c1b [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) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001772 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001773 ", 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,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001777 prefix, entry.eventTime, entry.deviceId,
1778 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1779 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1780 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1781 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001783 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1784 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1785 "x=%f, y=%f, pressure=%f, size=%f, "
1786 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1787 "orientation=%f",
1788 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1796 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1797 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800}
1801
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001802void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1803 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001804 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001805 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001806 if (DEBUG_DISPATCH_CYCLE) {
1807 ALOGD("dispatchEventToCurrentInputTargets");
1808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001810 updateInteractionTokensLocked(*eventEntry, inputTargets);
1811
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1813
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001816 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001817 sp<Connection> connection =
1818 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001819 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001820 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001822 if (DEBUG_FOCUS) {
1823 ALOGD("Dropping event delivery to target with channel '%s' because it "
1824 "is no longer registered with the input dispatcher.",
1825 inputTarget.inputChannel->getName().c_str());
1826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
1828 }
1829}
1830
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1832 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1833 // If the policy decides to close the app, we will get a channel removal event via
1834 // unregisterInputChannel, and will clean up the connection that way. We are already not
1835 // sending new pointers to the connection when it blocked, but focused events will continue to
1836 // pile up.
1837 ALOGW("Canceling events for %s because it is unresponsive",
1838 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001839 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001840 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1841 "application not responding");
1842 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 }
1844}
1845
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001846void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001847 if (DEBUG_FOCUS) {
1848 ALOGD("Resetting ANR timeouts.");
1849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850
1851 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001852 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001853 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854}
1855
Tiger Huang721e26f2018-07-24 22:26:19 +08001856/**
1857 * Get the display id that the given event should go to. If this event specifies a valid display id,
1858 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1859 * Focused display is the display that the user most recently interacted with.
1860 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001862 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001864 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001865 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1866 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001867 break;
1868 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001869 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001870 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1871 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 break;
1873 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001874 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001875 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001876 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001877 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001878 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001879 case EventEntry::Type::SENSOR:
1880 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001881 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001882 return ADISPLAY_ID_NONE;
1883 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001884 }
1885 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1886}
1887
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001888bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1889 const char* focusedWindowName) {
1890 if (mAnrTracker.empty()) {
1891 // already processed all events that we waited for
1892 mKeyIsWaitingForEventsTimeout = std::nullopt;
1893 return false;
1894 }
1895
1896 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1897 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001898 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001899 mKeyIsWaitingForEventsTimeout = currentTime +
1900 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1901 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 return true;
1903 }
1904
1905 // We still have pending events, and already started the timer
1906 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1907 return true; // Still waiting
1908 }
1909
1910 // Waited too long, and some connection still hasn't processed all motions
1911 // Just send the key to the focused window
1912 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1913 focusedWindowName);
1914 mKeyIsWaitingForEventsTimeout = std::nullopt;
1915 return false;
1916}
1917
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001918sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1919 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1920 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001921 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001922 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923
Tiger Huang721e26f2018-07-24 22:26:19 +08001924 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001925 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001926 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001927 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1928
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 // If there is no currently focused window and no focused application
1930 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1932 ALOGI("Dropping %s event because there is no focused window or focused application in "
1933 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001934 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001935 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
1937
Vishnu Nair062a8672021-09-03 16:07:44 -07001938 // Drop key events if requested by input feature
1939 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001940 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001941 }
1942
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001943 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1944 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1945 // start interacting with another application via touch (app switch). This code can be removed
1946 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1947 // an app is expected to have a focused window.
1948 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1949 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1950 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001951 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1952 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1953 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001954 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001955 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 ALOGW("Waiting because no window has focus but %s may eventually add a "
1957 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001958 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001959 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001960 outInjectionResult = InputEventInjectionResult::PENDING;
1961 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1963 // Already raised ANR. Drop the event
1964 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001965 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001966 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001967 } else {
1968 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001969 outInjectionResult = InputEventInjectionResult::PENDING;
1970 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001971 }
1972 }
1973
1974 // we have a valid, non-null focused window
1975 resetNoFocusedWindowTimeoutLocked();
1976
Prabir Pradhan5735a322022-04-11 17:23:34 +00001977 // Verify targeted injection.
1978 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1979 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001980 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1981 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
1983
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001984 if (focusedWindowHandle->getInfo()->inputConfig.test(
1985 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001987 outInjectionResult = InputEventInjectionResult::PENDING;
1988 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 }
1990
1991 // If the event is a key event, then we must wait for all previous events to
1992 // complete before delivering it because previous events may have the
1993 // side-effect of transferring focus to a different window and we want to
1994 // ensure that the following keys are sent to the new window.
1995 //
1996 // Suppose the user touches a button in a window then immediately presses "A".
1997 // If the button causes a pop-up window to appear then we want to ensure that
1998 // the "A" key is delivered to the new pop-up window. This is because users
1999 // often anticipate pending UI changes when typing on a keyboard.
2000 // To obtain this behavior, we must serialize key events with respect to all
2001 // prior input events.
2002 if (entry.type == EventEntry::Type::KEY) {
2003 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2004 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002005 outInjectionResult = InputEventInjectionResult::PENDING;
2006 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002010 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2011 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012}
2013
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014/**
2015 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2016 * that are currently unresponsive.
2017 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002018std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2019 const std::vector<Monitor>& monitors) const {
2020 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002022 [this](const Monitor& monitor) REQUIRES(mLock) {
2023 sp<Connection> connection =
2024 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 if (connection == nullptr) {
2026 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002027 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 return false;
2029 }
2030 if (!connection->responsive) {
2031 ALOGW("Unresponsive monitor %s will not get the new gesture",
2032 connection->inputChannel->getName().c_str());
2033 return false;
2034 }
2035 return true;
2036 });
2037 return responsiveMonitors;
2038}
2039
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002040/**
2041 * In general, touch should be always split between windows. Some exceptions:
2042 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2043 * from the same device, *and* the window that's receiving the current pointer does not support
2044 * split touch.
2045 * 2. Don't split mouse events
2046 */
2047bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2048 const MotionEntry& entry) const {
2049 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2050 // We should never split mouse events
2051 return false;
2052 }
2053 for (const TouchedWindow& touchedWindow : touchState.windows) {
2054 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2055 // Spy windows should not affect whether or not touch is split.
2056 continue;
2057 }
2058 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2059 continue;
2060 }
2061 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2062 // being sent there. For now, use deviceId from touch state.
2063 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2064 return false;
2065 }
2066 }
2067 return true;
2068}
2069
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002070std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002071 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2072 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002073 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002075 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 // For security reasons, we defer updating the touch state until we are sure that
2077 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002078 const int32_t displayId = entry.displayId;
2079 const int32_t action = entry.action;
2080 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
2082 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002083 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002084 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2085 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 // Copy current touch state into tempTouchState.
2088 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2089 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002090 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002091 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002092 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2093 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002094 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002095 }
2096
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002097 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002098 const bool switchedDevice = (oldState != nullptr) &&
2099 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002100
2101 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2102 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2103 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2104 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2105 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002106 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 if (newGesture) {
2108 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002109 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002110 ALOGI("Dropping event because a pointer for a different device is already down "
2111 "in display %" PRId32,
2112 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002113 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002114 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002115 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002117 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 tempTouchState.deviceId = entry.deviceId;
2119 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002121 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002122 ALOGI("Dropping move event because a pointer for a different device is already active "
2123 "in display %" PRId32,
2124 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002125 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002126 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002127 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 }
2129
2130 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2131 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002132 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002133 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002134 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002135 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002136 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002137 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002138
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002140 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002141 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2142 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002144 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002145 }
2146
Prabir Pradhan5735a322022-04-11 17:23:34 +00002147 // Verify targeted injection.
2148 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2149 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002150 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002151 newTouchedWindowHandle = nullptr;
2152 goto Failed;
2153 }
2154
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002155 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002156 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2158 // New window supports splitting, but we should never split mouse events.
2159 isSplit = !isFromMouse;
2160 } else if (isSplit) {
2161 // New window does not support splitting but we have already split events.
2162 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163 newTouchedWindowHandle = nullptr;
2164 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165 } else {
2166 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002167 // be delivered to a new window which supports split touch. Pointers from a mouse device
2168 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002169 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 }
2171
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002172 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002173 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002174 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2175 newHoverWindowHandle = nullptr;
2176 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002177 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002178 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179 }
2180
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002181 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002182 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002184 // Process the foreground window first so that it is the first to receive the event.
2185 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186 }
2187
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002188 if (newTouchedWindows.empty()) {
2189 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2190 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002191 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002192 goto Failed;
2193 }
2194
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002195 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002196 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002197 continue;
2198 }
2199
2200 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002201 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002202
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002203 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2204 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002205 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002206 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002207
2208 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002209 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002210 }
2211 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002212 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002213 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002214 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002215 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002216
2217 // Update the temporary touch state.
2218 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002219 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002220
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002221 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2222 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002224
2225 // If any existing window is pilfering pointers from newly added window, remove it
2226 BitSet32 canceledPointers = BitSet32(0);
2227 for (const TouchedWindow& window : tempTouchState.windows) {
2228 if (window.isPilferingPointers) {
2229 canceledPointers |= window.pointerIds;
2230 }
2231 }
2232 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 } else {
2234 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2235
2236 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002237 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002238 ALOGD_IF(DEBUG_FOCUS,
2239 "Dropping event because the pointer is not down or we previously "
2240 "dropped the pointer down event in display %" PRId32 ": %s",
2241 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002242 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 goto Failed;
2244 }
2245
arthurhung6d4bed92021-03-17 11:59:33 +08002246 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002247
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002249 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002251 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002252 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002253 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002254 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002255 newTouchedWindowHandle =
2256 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002257
Prabir Pradhan5735a322022-04-11 17:23:34 +00002258 // Verify targeted injection.
2259 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2260 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002261 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002262 newTouchedWindowHandle = nullptr;
2263 goto Failed;
2264 }
2265
Vishnu Nair062a8672021-09-03 16:07:44 -07002266 // Drop touch events if requested by input feature
2267 if (newTouchedWindowHandle != nullptr &&
2268 shouldDropInput(entry, newTouchedWindowHandle)) {
2269 newTouchedWindowHandle = nullptr;
2270 }
2271
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2273 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002274 if (DEBUG_FOCUS) {
2275 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2276 oldTouchedWindowHandle->getName().c_str(),
2277 newTouchedWindowHandle->getName().c_str(), displayId);
2278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002281 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002282 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283
2284 // Make a slippery entrance into the new window.
2285 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002286 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
2288
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002289 ftl::Flags<InputTarget::Flags> targetFlags =
2290 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002291 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002292 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002295 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002298 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002299 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002300 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
2303 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002304 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002305 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2306 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308 }
Arthur Hung96483742022-11-15 03:30:48 +00002309
2310 // Update the pointerIds for non-splittable when it received pointer down.
2311 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2312 // If no split, we suppose all touched windows should receive pointer down.
2313 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2314 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2315 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2316 // Ignore drag window for it should just track one pointer.
2317 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2318 continue;
2319 }
2320 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2321 }
2322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 }
2324
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002325 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002327 // Let the previous window know that the hover sequence is over, unless we already did
2328 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002329 if (mLastHoverWindowHandle != nullptr &&
2330 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2331 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002332 if (DEBUG_HOVER) {
2333 ALOGD("Sending hover exit event to window %s.",
2334 mLastHoverWindowHandle->getName().c_str());
2335 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002337 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2338 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340
Garfield Tandf26e862020-07-01 20:18:19 -07002341 // Let the new window know that the hover sequence is starting, unless we already did it
2342 // when dispatching it as is to newTouchedWindowHandle.
2343 if (newHoverWindowHandle != nullptr &&
2344 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2345 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002346 if (DEBUG_HOVER) {
2347 ALOGD("Sending hover enter event to window %s.",
2348 newHoverWindowHandle->getName().c_str());
2349 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002350 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002351 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002352 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 }
2354 }
2355
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002356 // Ensure that we have at least one foreground window or at least one window that cannot be a
2357 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2358 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2359 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002360 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2361 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002362 return !canReceiveForegroundTouches(
2363 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002364 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002365 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002366 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2367 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002368 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002369 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371
Prabir Pradhan5735a322022-04-11 17:23:34 +00002372 // Ensure that all touched windows are valid for injection.
2373 if (entry.injectionState != nullptr) {
2374 std::string errs;
2375 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002376 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002377 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2378 // dispatched to any uid, since the coords will be zeroed out later.
2379 continue;
2380 }
2381 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2382 if (err) errs += "\n - " + *err;
2383 }
2384 if (!errs.empty()) {
2385 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2386 "%d:%s",
2387 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002388 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002389 goto Failed;
2390 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002391 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 // Check whether windows listening for outside touches are owned by the same UID. If it is
2394 // set the policy flag that we will not reveal coordinate information to this window.
2395 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002396 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002397 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002398 if (foregroundWindowHandle) {
2399 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002400 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002401 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002402 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2403 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2404 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002405 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002406 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
2409 }
2410 }
2411 }
2412
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 // If this is the first pointer going down and the touched window has a wallpaper
2414 // then also add the touched wallpaper windows so they are locked in for the duration
2415 // of the touch gesture.
2416 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2417 // engine only supports touch events. We would need to add a mechanism similar
2418 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2419 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002420 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002421 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002422 if (foregroundWindowHandle &&
2423 foregroundWindowHandle->getInfo()->inputConfig.test(
2424 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002425 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002426 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002427 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2428 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002430 windowHandle->getInfo()->inputConfig.test(
2431 WindowInfo::InputConfig::IS_WALLPAPER)) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002432 BitSet32 pointerIds;
2433 pointerIds.markBit(entry.pointerProperties[0].id);
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002434 tempTouchState.addOrUpdateWindow(windowHandle,
2435 InputTarget::Flags::WINDOW_IS_OBSCURED |
2436 InputTarget::Flags::
2437 WINDOW_IS_PARTIALLY_OBSCURED |
2438 InputTarget::Flags::DISPATCH_AS_IS,
Arthur Hung74c248d2022-11-23 07:09:59 +00002439 pointerIds, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441 }
2442 }
2443 }
2444
2445 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002446 touchedWindows = tempTouchState.windows;
2447 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448
2449 // Drop the outside or hover touch windows since we will not care about them
2450 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002451 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452
2453Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002455 if (switchedDevice) {
2456 if (DEBUG_FOCUS) {
2457 ALOGD("Conflicting pointer actions: Switched to a different device.");
2458 }
2459 *outConflictingPointerActions = true;
2460 }
2461
2462 if (isHoverAction) {
2463 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002464 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002465 ALOGD_IF(DEBUG_FOCUS,
2466 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002467 *outConflictingPointerActions = true;
2468 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002469 tempTouchState.reset();
2470 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2471 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2472 tempTouchState.deviceId = entry.deviceId;
2473 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002474 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002475 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2476 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2477 // All pointers up or canceled.
2478 tempTouchState.reset();
2479 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2480 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002481 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002482 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002483 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002484 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002485 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2486 // One pointer went up.
2487 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2488 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002490 for (size_t i = 0; i < tempTouchState.windows.size();) {
2491 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2492 touchedWindow.pointerIds.clearBit(pointerId);
2493 if (touchedWindow.pointerIds.isEmpty()) {
2494 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2495 continue;
2496 }
2497 i += 1;
2498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 }
2500
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002501 // Save changes unless the action was scroll in which case the temporary touch
2502 // state was only valid for this one action.
2503 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002504 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002505 mTouchStatesByDisplay[displayId] = tempTouchState;
2506 } else {
2507 mTouchStatesByDisplay.erase(displayId);
2508 }
2509 }
2510
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002511 if (tempTouchState.windows.empty()) {
2512 mTouchStatesByDisplay.erase(displayId);
2513 }
2514
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002515 // Update hover state.
2516 mLastHoverWindowHandle = newHoverWindowHandle;
2517
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002518 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519}
2520
arthurhung6d4bed92021-03-17 11:59:33 +08002521void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002522 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2523 // have an explicit reason to support it.
2524 constexpr bool isStylus = false;
2525
chaviw98318de2021-05-19 16:45:23 -05002526 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002527 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002528 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002529 if (dropWindow) {
2530 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002531 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002532 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002533 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002534 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002535 }
2536 mDragState.reset();
2537}
2538
2539void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002540 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002541 return;
2542 }
2543
arthurhung6d4bed92021-03-17 11:59:33 +08002544 if (!mDragState->isStartDrag) {
2545 mDragState->isStartDrag = true;
2546 mDragState->isStylusButtonDownAtStart =
2547 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2548 }
2549
Arthur Hung54745652022-04-20 07:17:41 +00002550 // Find the pointer index by id.
2551 int32_t pointerIndex = 0;
2552 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2553 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2554 if (pointerProperties.id == mDragState->pointerId) {
2555 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002556 }
Arthur Hung54745652022-04-20 07:17:41 +00002557 }
arthurhung6d4bed92021-03-17 11:59:33 +08002558
Arthur Hung54745652022-04-20 07:17:41 +00002559 if (uint32_t(pointerIndex) == entry.pointerCount) {
2560 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002561 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002562 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002563 return;
2564 }
2565
2566 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2567 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2568 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2569
2570 switch (maskedAction) {
2571 case AMOTION_EVENT_ACTION_MOVE: {
2572 // Handle the special case : stylus button no longer pressed.
2573 bool isStylusButtonDown =
2574 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2575 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2576 finishDragAndDrop(entry.displayId, x, y);
2577 return;
2578 }
2579
2580 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2581 // until we have an explicit reason to support it.
2582 constexpr bool isStylus = false;
2583
2584 const sp<WindowInfoHandle> hoverWindowHandle =
2585 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2586 isStylus, false /*addOutsideTargets*/,
2587 true /*ignoreDragWindow*/);
2588 // enqueue drag exit if needed.
2589 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2590 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2591 if (mDragState->dragHoverWindowHandle != nullptr) {
2592 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2593 y);
2594 }
2595 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2596 }
2597 // enqueue drag location if needed.
2598 if (hoverWindowHandle != nullptr) {
2599 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2600 }
2601 break;
2602 }
2603
2604 case AMOTION_EVENT_ACTION_POINTER_UP:
2605 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2606 break;
2607 }
2608 // The drag pointer is up.
2609 [[fallthrough]];
2610 case AMOTION_EVENT_ACTION_UP:
2611 finishDragAndDrop(entry.displayId, x, y);
2612 break;
2613 case AMOTION_EVENT_ACTION_CANCEL: {
2614 ALOGD("Receiving cancel when drag and drop.");
2615 sendDropWindowCommandLocked(nullptr, 0, 0);
2616 mDragState.reset();
2617 break;
2618 }
arthurhungb89ccb02020-12-30 16:19:01 +08002619 }
2620}
2621
chaviw98318de2021-05-19 16:45:23 -05002622void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002623 ftl::Flags<InputTarget::Flags> targetFlags,
2624 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002625 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002626 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002627 std::vector<InputTarget>::iterator it =
2628 std::find_if(inputTargets.begin(), inputTargets.end(),
2629 [&windowHandle](const InputTarget& inputTarget) {
2630 return inputTarget.inputChannel->getConnectionToken() ==
2631 windowHandle->getToken();
2632 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002633
chaviw98318de2021-05-19 16:45:23 -05002634 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002635
2636 if (it == inputTargets.end()) {
2637 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002638 std::shared_ptr<InputChannel> inputChannel =
2639 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002640 if (inputChannel == nullptr) {
2641 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2642 return;
2643 }
2644 inputTarget.inputChannel = inputChannel;
2645 inputTarget.flags = targetFlags;
2646 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002647 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002648 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2649 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002650 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002651 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002652 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002653 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002654 inputTargets.push_back(inputTarget);
2655 it = inputTargets.end() - 1;
2656 }
2657
2658 ALOG_ASSERT(it->flags == targetFlags);
2659 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2660
chaviw1ff3d1e2020-07-01 15:53:47 -07002661 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662}
2663
Michael Wright3dd60e22019-03-27 22:06:44 +00002664void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002665 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002666 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2667 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002668
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002669 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2670 InputTarget target;
2671 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002672 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002673 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2674 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002675 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2676 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002677 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002678 target.setDefaultPointerTransform(target.displayTransform);
2679 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 }
2681}
2682
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683/**
2684 * Indicate whether one window handle should be considered as obscuring
2685 * another window handle. We only check a few preconditions. Actually
2686 * checking the bounds is left to the caller.
2687 */
chaviw98318de2021-05-19 16:45:23 -05002688static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2689 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002690 // Compare by token so cloned layers aren't counted
2691 if (haveSameToken(windowHandle, otherHandle)) {
2692 return false;
2693 }
2694 auto info = windowHandle->getInfo();
2695 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002696 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002697 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002698 } else if (otherInfo->alpha == 0 &&
2699 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002700 // Those act as if they were invisible, so we don't need to flag them.
2701 // We do want to potentially flag touchable windows even if they have 0
2702 // opacity, since they can consume touches and alter the effects of the
2703 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002704 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002705 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2706 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002707 } else if (info->ownerUid == otherInfo->ownerUid) {
2708 // If ownerUid is the same we don't generate occlusion events as there
2709 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002710 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002711 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002712 return false;
2713 } else if (otherInfo->displayId != info->displayId) {
2714 return false;
2715 }
2716 return true;
2717}
2718
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002719/**
2720 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2721 * untrusted, one should check:
2722 *
2723 * 1. If result.hasBlockingOcclusion is true.
2724 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2725 * BLOCK_UNTRUSTED.
2726 *
2727 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2728 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2729 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2730 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2731 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2732 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2733 *
2734 * If neither of those is true, then it means the touch can be allowed.
2735 */
2736InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002737 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2738 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002739 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002740 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002741 TouchOcclusionInfo info;
2742 info.hasBlockingOcclusion = false;
2743 info.obscuringOpacity = 0;
2744 info.obscuringUid = -1;
2745 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002746 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002747 if (windowHandle == otherHandle) {
2748 break; // All future windows are below us. Exit early.
2749 }
chaviw98318de2021-05-19 16:45:23 -05002750 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002751 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2752 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002753 if (DEBUG_TOUCH_OCCLUSION) {
2754 info.debugInfo.push_back(
2755 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2756 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002757 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2758 // we perform the checks below to see if the touch can be propagated or not based on the
2759 // window's touch occlusion mode
2760 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2761 info.hasBlockingOcclusion = true;
2762 info.obscuringUid = otherInfo->ownerUid;
2763 info.obscuringPackage = otherInfo->packageName;
2764 break;
2765 }
2766 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2767 uint32_t uid = otherInfo->ownerUid;
2768 float opacity =
2769 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2770 // Given windows A and B:
2771 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2772 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2773 opacityByUid[uid] = opacity;
2774 if (opacity > info.obscuringOpacity) {
2775 info.obscuringOpacity = opacity;
2776 info.obscuringUid = uid;
2777 info.obscuringPackage = otherInfo->packageName;
2778 }
2779 }
2780 }
2781 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002782 if (DEBUG_TOUCH_OCCLUSION) {
2783 info.debugInfo.push_back(
2784 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2785 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002786 return info;
2787}
2788
chaviw98318de2021-05-19 16:45:23 -05002789std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002790 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002791 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2792 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2793 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2794 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002795 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2796 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2797 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2798 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2799 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002800 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002801 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002802}
2803
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002804bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2805 if (occlusionInfo.hasBlockingOcclusion) {
2806 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2807 occlusionInfo.obscuringUid);
2808 return false;
2809 }
2810 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2811 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2812 "%.2f, maximum allowed = %.2f)",
2813 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2814 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2815 return false;
2816 }
2817 return true;
2818}
2819
chaviw98318de2021-05-19 16:45:23 -05002820bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002823 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2824 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002825 if (windowHandle == otherHandle) {
2826 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 }
chaviw98318de2021-05-19 16:45:23 -05002828 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002829 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002830 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 return true;
2832 }
2833 }
2834 return false;
2835}
2836
chaviw98318de2021-05-19 16:45:23 -05002837bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002838 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002839 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2840 const WindowInfo* windowInfo = windowHandle->getInfo();
2841 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002842 if (windowHandle == otherHandle) {
2843 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002844 }
chaviw98318de2021-05-19 16:45:23 -05002845 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002846 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002847 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002848 return true;
2849 }
2850 }
2851 return false;
2852}
2853
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002854std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002855 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002856 if (applicationHandle != nullptr) {
2857 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002858 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 } else {
2860 return applicationHandle->getName();
2861 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002862 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002863 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002865 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 }
2867}
2868
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002869void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002870 if (!isUserActivityEvent(eventEntry)) {
2871 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002872 return;
2873 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002874 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002875 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002876 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002877 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002878 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002879 if (DEBUG_DISPATCH_CYCLE) {
2880 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 return;
2883 }
2884 }
2885
2886 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002887 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002888 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2890 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 return;
2892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 eventType = USER_ACTIVITY_EVENT_TOUCH;
2896 }
2897 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002899 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002900 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2901 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 return;
2903 }
2904 eventType = USER_ACTIVITY_EVENT_BUTTON;
2905 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002907 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002908 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002909 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002910 break;
2911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 }
2913
Prabir Pradhancef936d2021-07-21 16:17:52 +00002914 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2915 REQUIRES(mLock) {
2916 scoped_unlock unlock(mLock);
2917 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2918 };
2919 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920}
2921
2922void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002924 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002925 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002926 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002928 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002929 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002930 ATRACE_NAME(message.c_str());
2931 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002932 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002933 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002934 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002935 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002936 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2937 inputTarget.getPointerInfoString().c_str());
2938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
2940 // Skip this event if the connection status is not normal.
2941 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002942 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002943 if (DEBUG_DISPATCH_CYCLE) {
2944 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002945 connection->getInputChannelName().c_str(),
2946 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 return;
2949 }
2950
2951 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002952 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002953 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002954 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002955 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002957 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002958 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002959 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2960 "Splitting motion events requires a down time to be set for the "
2961 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002962 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002963 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2964 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 if (!splitMotionEntry) {
2966 return; // split event was dropped
2967 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002968 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2969 std::string reason = std::string("reason=pointer cancel on split window");
2970 android_log_event_list(LOGTAG_INPUT_CANCEL)
2971 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2972 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002973 if (DEBUG_FOCUS) {
2974 ALOGD("channel '%s' ~ Split motion event.",
2975 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002976 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002977 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002978 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2979 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 return;
2981 }
2982 }
2983
2984 // Not splitting. Enqueue dispatch entries for the event as is.
2985 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2986}
2987
2988void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002990 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002991 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002992 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002994 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002995 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002996 ATRACE_NAME(message.c_str());
2997 }
2998
hongzuo liu95785e22022-09-06 02:51:35 +00002999 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000
3001 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003002 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003003 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003004 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003005 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003006 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003007 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003008 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003009 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003010 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003011 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003012 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003013 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
3015 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003016 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 startDispatchCycleLocked(currentTime, connection);
3018 }
3019}
3020
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003022 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003023 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003024 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003025 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3027 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003028 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003029 ATRACE_NAME(message.c_str());
3030 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003031 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3032 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 return;
3034 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003035
3036 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3037 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038
3039 // This is a new event.
3040 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003041 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003042 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003044 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3045 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003048 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003049 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003051 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003052 dispatchEntry->resolvedAction = keyEntry.action;
3053 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3056 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003057 if (DEBUG_DISPATCH_CYCLE) {
3058 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3059 "event",
3060 connection->getInputChannelName().c_str());
3061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 return; // skip the inconsistent event
3063 }
3064 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003067 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003068 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003069 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3070 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3071 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3072 static_cast<int32_t>(IdGenerator::Source::OTHER);
3073 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003074 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003076 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003078 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003080 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003082 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3084 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003085 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003086 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 }
3088 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3090 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003091 if (DEBUG_DISPATCH_CYCLE) {
3092 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3093 "enter event",
3094 connection->getInputChannelName().c_str());
3095 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003096 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3097 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003101 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003102 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3104 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003105 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3110 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003111 if (DEBUG_DISPATCH_CYCLE) {
3112 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3113 "event",
3114 connection->getInputChannelName().c_str());
3115 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 return; // skip the inconsistent event
3117 }
3118
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003119 dispatchEntry->resolvedEventId =
3120 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3121 ? mIdGenerator.nextId()
3122 : motionEntry.id;
3123 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3124 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3125 ") to MotionEvent(id=0x%" PRIx32 ").",
3126 motionEntry.id, dispatchEntry->resolvedEventId);
3127 ATRACE_NAME(message.c_str());
3128 }
3129
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003130 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3131 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3132 // Skip reporting pointer down outside focus to the policy.
3133 break;
3134 }
3135
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003137 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138
3139 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003141 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003142 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003143 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3144 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003145 break;
3146 }
Chris Yef59a2f42020-10-16 12:55:26 -07003147 case EventEntry::Type::SENSOR: {
3148 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3149 break;
3150 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 case EventEntry::Type::CONFIGURATION_CHANGED:
3152 case EventEntry::Type::DEVICE_RESET: {
3153 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003154 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003155 break;
3156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
3159 // Remember that we are waiting for this dispatch to complete.
3160 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003161 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
3163
3164 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003165 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003166 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003167}
3168
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003169/**
3170 * This function is purely for debugging. It helps us understand where the user interaction
3171 * was taking place. For example, if user is touching launcher, we will see a log that user
3172 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3173 * We will see both launcher and wallpaper in that list.
3174 * Once the interaction with a particular set of connections starts, no new logs will be printed
3175 * until the set of interacted connections changes.
3176 *
3177 * The following items are skipped, to reduce the logspam:
3178 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3179 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3180 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3181 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3182 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003183 */
3184void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3185 const std::vector<InputTarget>& targets) {
3186 // Skip ACTION_UP events, and all events other than keys and motions
3187 if (entry.type == EventEntry::Type::KEY) {
3188 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3189 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3190 return;
3191 }
3192 } else if (entry.type == EventEntry::Type::MOTION) {
3193 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3194 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3195 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3196 return;
3197 }
3198 } else {
3199 return; // Not a key or a motion
3200 }
3201
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003202 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003203 std::vector<sp<Connection>> newConnections;
3204 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003205 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003206 continue; // Skip windows that receive ACTION_OUTSIDE
3207 }
3208
3209 sp<IBinder> token = target.inputChannel->getConnectionToken();
3210 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003211 if (connection == nullptr) {
3212 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003213 }
3214 newConnectionTokens.insert(std::move(token));
3215 newConnections.emplace_back(connection);
3216 }
3217 if (newConnectionTokens == mInteractionConnectionTokens) {
3218 return; // no change
3219 }
3220 mInteractionConnectionTokens = newConnectionTokens;
3221
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003222 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003223 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003224 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003225 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003226 std::string message = "Interaction with: " + targetList;
3227 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003228 message += "<none>";
3229 }
3230 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3231}
3232
chaviwfd6d3512019-03-25 13:23:49 -07003233void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003234 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003235 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003236 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3237 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003238 return;
3239 }
3240
Vishnu Nairc519ff72021-01-21 08:23:08 -08003241 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003242 if (focusedToken == token) {
3243 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003244 return;
3245 }
3246
Prabir Pradhancef936d2021-07-21 16:17:52 +00003247 auto command = [this, token]() REQUIRES(mLock) {
3248 scoped_unlock unlock(mLock);
3249 mPolicy->onPointerDownOutsideFocus(token);
3250 };
3251 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252}
3253
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003254status_t InputDispatcher::publishMotionEvent(Connection& connection,
3255 DispatchEntry& dispatchEntry) const {
3256 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3257 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3258
3259 PointerCoords scaledCoords[MAX_POINTERS];
3260 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3261
3262 // Set the X and Y offset and X and Y scale depending on the input source.
3263 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003264 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003265 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3266 if (globalScaleFactor != 1.0f) {
3267 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3268 scaledCoords[i] = motionEntry.pointerCoords[i];
3269 // Don't apply window scale here since we don't want scale to affect raw
3270 // coordinates. The scale will be sent back to the client and applied
3271 // later when requesting relative coordinates.
3272 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3273 1 /* windowYScale */);
3274 }
3275 usingCoords = scaledCoords;
3276 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003278 // We don't want the dispatch target to know the coordinates
3279 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3280 scaledCoords[i].clear();
3281 }
3282 usingCoords = scaledCoords;
3283 }
3284
3285 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3286
3287 // Publish the motion event.
3288 return connection.inputPublisher
3289 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3290 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3291 std::move(hmac), dispatchEntry.resolvedAction,
3292 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3293 motionEntry.edgeFlags, motionEntry.metaState,
3294 motionEntry.buttonState, motionEntry.classification,
3295 dispatchEntry.transform, motionEntry.xPrecision,
3296 motionEntry.yPrecision, motionEntry.xCursorPosition,
3297 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3298 motionEntry.downTime, motionEntry.eventTime,
3299 motionEntry.pointerCount, motionEntry.pointerProperties,
3300 usingCoords);
3301}
3302
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003304 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003305 if (ATRACE_ENABLED()) {
3306 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003308 ATRACE_NAME(message.c_str());
3309 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003310 if (DEBUG_DISPATCH_CYCLE) {
3311 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003314 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003315 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003317 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003318 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
3320 // Publish the event.
3321 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003322 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3323 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003324 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003325 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3326 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003329 status = connection->inputPublisher
3330 .publishKeyEvent(dispatchEntry->seq,
3331 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3332 keyEntry.source, keyEntry.displayId,
3333 std::move(hmac), dispatchEntry->resolvedAction,
3334 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3335 keyEntry.scanCode, keyEntry.metaState,
3336 keyEntry.repeatCount, keyEntry.downTime,
3337 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 }
3340
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003341 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003342 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 break;
3344 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003345
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003346 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003347 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003348 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003349 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003350 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003351 break;
3352 }
3353
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003354 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3355 const TouchModeEntry& touchModeEntry =
3356 static_cast<const TouchModeEntry&>(eventEntry);
3357 status = connection->inputPublisher
3358 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3359 touchModeEntry.inTouchMode);
3360
3361 break;
3362 }
3363
Prabir Pradhan99987712020-11-10 18:43:05 -08003364 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3365 const auto& captureEntry =
3366 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3367 status = connection->inputPublisher
3368 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003369 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003370 break;
3371 }
3372
arthurhungb89ccb02020-12-30 16:19:01 +08003373 case EventEntry::Type::DRAG: {
3374 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3375 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3376 dragEntry.id, dragEntry.x,
3377 dragEntry.y,
3378 dragEntry.isExiting);
3379 break;
3380 }
3381
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003382 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003383 case EventEntry::Type::DEVICE_RESET:
3384 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003385 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003386 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 }
3390
3391 // Check the result.
3392 if (status) {
3393 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003394 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 "This is unexpected because the wait queue is empty, so the pipe "
3397 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003398 "event to it, status=%s(%d)",
3399 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3400 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3402 } else {
3403 // Pipe is full and we are waiting for the app to finish process some events
3404 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003405 if (DEBUG_DISPATCH_CYCLE) {
3406 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3407 "waiting for the application to catch up",
3408 connection->getInputChannelName().c_str());
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411 } else {
3412 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003413 "status=%s(%d)",
3414 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3415 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3417 }
3418 return;
3419 }
3420
3421 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003422 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3423 connection->outboundQueue.end(),
3424 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003425 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003426 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003427 if (connection->responsive) {
3428 mAnrTracker.insert(dispatchEntry->timeoutTime,
3429 connection->inputChannel->getConnectionToken());
3430 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003431 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433}
3434
chaviw09c8d2d2020-08-24 15:48:26 -07003435std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3436 size_t size;
3437 switch (event.type) {
3438 case VerifiedInputEvent::Type::KEY: {
3439 size = sizeof(VerifiedKeyEvent);
3440 break;
3441 }
3442 case VerifiedInputEvent::Type::MOTION: {
3443 size = sizeof(VerifiedMotionEvent);
3444 break;
3445 }
3446 }
3447 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3448 return mHmacKeyManager.sign(start, size);
3449}
3450
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003451const std::array<uint8_t, 32> InputDispatcher::getSignature(
3452 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003453 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3454 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003455 // Only sign events up and down events as the purely move events
3456 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003457 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003458 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003459
3460 VerifiedMotionEvent verifiedEvent =
3461 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3462 verifiedEvent.actionMasked = actionMasked;
3463 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3464 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003465}
3466
3467const std::array<uint8_t, 32> InputDispatcher::getSignature(
3468 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3469 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3470 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3471 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003472 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003473}
3474
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003476 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003477 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003478 if (DEBUG_DISPATCH_CYCLE) {
3479 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3480 connection->getInputChannelName().c_str(), seq, toString(handled));
3481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003483 if (connection->status == Connection::Status::BROKEN ||
3484 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 return;
3486 }
3487
3488 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003489 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3490 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3491 };
3492 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493}
3494
3495void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003496 const sp<Connection>& connection,
3497 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003498 if (DEBUG_DISPATCH_CYCLE) {
3499 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3500 connection->getInputChannelName().c_str(), toString(notify));
3501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
3503 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003504 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003505 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003506 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003507 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508
3509 // The connection appears to be unrecoverably broken.
3510 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003511 if (connection->status == Connection::Status::NORMAL) {
3512 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513
3514 if (notify) {
3515 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003516 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3517 connection->getInputChannelName().c_str());
3518
3519 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003520 scoped_unlock unlock(mLock);
3521 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3522 };
3523 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 }
3525 }
3526}
3527
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003528void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3529 while (!queue.empty()) {
3530 DispatchEntry* dispatchEntry = queue.front();
3531 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003532 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534}
3535
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003536void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003538 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 }
3540 delete dispatchEntry;
3541}
3542
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003543int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3544 std::scoped_lock _l(mLock);
3545 sp<Connection> connection = getConnectionLocked(connectionToken);
3546 if (connection == nullptr) {
3547 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3548 connectionToken.get(), events);
3549 return 0; // remove the callback
3550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003552 bool notify;
3553 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3554 if (!(events & ALOOPER_EVENT_INPUT)) {
3555 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3556 "events=0x%x",
3557 connection->getInputChannelName().c_str(), events);
3558 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 }
3560
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003561 nsecs_t currentTime = now();
3562 bool gotOne = false;
3563 status_t status = OK;
3564 for (;;) {
3565 Result<InputPublisher::ConsumerResponse> result =
3566 connection->inputPublisher.receiveConsumerResponse();
3567 if (!result.ok()) {
3568 status = result.error().code();
3569 break;
3570 }
3571
3572 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3573 const InputPublisher::Finished& finish =
3574 std::get<InputPublisher::Finished>(*result);
3575 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3576 finish.consumeTime);
3577 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003578 if (shouldReportMetricsForConnection(*connection)) {
3579 const InputPublisher::Timeline& timeline =
3580 std::get<InputPublisher::Timeline>(*result);
3581 mLatencyTracker
3582 .trackGraphicsLatency(timeline.inputEventId,
3583 connection->inputChannel->getConnectionToken(),
3584 std::move(timeline.graphicsTimeline));
3585 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003586 }
3587 gotOne = true;
3588 }
3589 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003590 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003591 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 return 1;
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003596 notify = status != DEAD_OBJECT || !connection->monitor;
3597 if (notify) {
3598 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3599 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3600 status);
3601 }
3602 } else {
3603 // Monitor channels are never explicitly unregistered.
3604 // We do it automatically when the remote endpoint is closed so don't warn about them.
3605 const bool stillHaveWindowHandle =
3606 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3607 notify = !connection->monitor && stillHaveWindowHandle;
3608 if (notify) {
3609 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3610 connection->getInputChannelName().c_str(), events);
3611 }
3612 }
3613
3614 // Remove the channel.
3615 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3616 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617}
3618
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003621 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003622 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624}
3625
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003626void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003627 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003628 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003629 for (const Monitor& monitor : monitors) {
3630 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003631 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003632 }
3633}
3634
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003636 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003637 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003638 if (connection == nullptr) {
3639 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003641
3642 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643}
3644
3645void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3646 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003647 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 return;
3649 }
3650
3651 nsecs_t currentTime = now();
3652
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003653 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003654 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003656 if (cancelationEvents.empty()) {
3657 return;
3658 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003659 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3660 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3661 "with reality: %s, mode=%d.",
3662 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3663 options.mode);
3664 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003665
Arthur Hungb3307ee2021-10-14 10:57:37 +00003666 std::string reason = std::string("reason=").append(options.reason);
3667 android_log_event_list(LOGTAG_INPUT_CANCEL)
3668 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3669
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003671 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003672 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3673 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003674 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003675 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 target.globalScaleFactor = windowInfo->globalScaleFactor;
3677 }
3678 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003679 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003680
hongzuo liu95785e22022-09-06 02:51:35 +00003681 const bool wasEmpty = connection->outboundQueue.empty();
3682
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003683 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003684 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003685 switch (cancelationEventEntry->type) {
3686 case EventEntry::Type::KEY: {
3687 logOutboundKeyDetails("cancel - ",
3688 static_cast<const KeyEntry&>(*cancelationEventEntry));
3689 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003691 case EventEntry::Type::MOTION: {
3692 logOutboundMotionDetails("cancel - ",
3693 static_cast<const MotionEntry&>(*cancelationEventEntry));
3694 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003696 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003697 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003698 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3699 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003700 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003701 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003702 break;
3703 }
3704 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003705 case EventEntry::Type::DEVICE_RESET:
3706 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003707 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003708 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003709 break;
3710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003713 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003714 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003716
hongzuo liu95785e22022-09-06 02:51:35 +00003717 // If the outbound queue was previously empty, start the dispatch cycle going.
3718 if (wasEmpty && !connection->outboundQueue.empty()) {
3719 startDispatchCycleLocked(currentTime, connection);
3720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721}
3722
Svet Ganov5d3bc372020-01-26 23:11:07 -08003723void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003724 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003725 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 return;
3727 }
3728
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003729 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003730 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731
3732 if (downEvents.empty()) {
3733 return;
3734 }
3735
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003736 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003737 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3738 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003739 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003740
3741 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003742 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3744 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003745 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003746 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003747 target.globalScaleFactor = windowInfo->globalScaleFactor;
3748 }
3749 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003750 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003751
hongzuo liu95785e22022-09-06 02:51:35 +00003752 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003753 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003754 switch (downEventEntry->type) {
3755 case EventEntry::Type::MOTION: {
3756 logOutboundMotionDetails("down - ",
3757 static_cast<const MotionEntry&>(*downEventEntry));
3758 break;
3759 }
3760
3761 case EventEntry::Type::KEY:
3762 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003763 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003764 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003765 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003766 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003767 case EventEntry::Type::SENSOR:
3768 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003769 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003770 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003771 break;
3772 }
3773 }
3774
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003775 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003776 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003777 }
3778
hongzuo liu95785e22022-09-06 02:51:35 +00003779 // If the outbound queue was previously empty, start the dispatch cycle going.
3780 if (wasEmpty && !connection->outboundQueue.empty()) {
3781 startDispatchCycleLocked(downTime, connection);
3782 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003783}
3784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003785std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003786 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 ALOG_ASSERT(pointerIds.value != 0);
3788
3789 uint32_t splitPointerIndexMap[MAX_POINTERS];
3790 PointerProperties splitPointerProperties[MAX_POINTERS];
3791 PointerCoords splitPointerCoords[MAX_POINTERS];
3792
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003793 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 uint32_t splitPointerCount = 0;
3795
3796 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003797 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003799 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 uint32_t pointerId = uint32_t(pointerProperties.id);
3801 if (pointerIds.hasBit(pointerId)) {
3802 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3803 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3804 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003805 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 splitPointerCount += 1;
3807 }
3808 }
3809
3810 if (splitPointerCount != pointerIds.count()) {
3811 // This is bad. We are missing some of the pointers that we expected to deliver.
3812 // Most likely this indicates that we received an ACTION_MOVE events that has
3813 // different pointer ids than we expected based on the previous ACTION_DOWN
3814 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3815 // in this way.
3816 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003817 "we expected there to be %d pointers. This probably means we received "
3818 "a broken sequence of pointer ids from the input device.",
3819 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003820 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
3822
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003823 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3826 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3828 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003829 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 uint32_t pointerId = uint32_t(pointerProperties.id);
3831 if (pointerIds.hasBit(pointerId)) {
3832 if (pointerIds.count() == 1) {
3833 // The first/last pointer went down/up.
3834 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003835 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003836 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3837 ? AMOTION_EVENT_ACTION_CANCEL
3838 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 } else {
3840 // A secondary pointer went down/up.
3841 uint32_t splitPointerIndex = 0;
3842 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3843 splitPointerIndex += 1;
3844 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003845 action = maskedAction |
3846 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 }
3848 } else {
3849 // An unrelated pointer changed.
3850 action = AMOTION_EVENT_ACTION_MOVE;
3851 }
3852 }
3853
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003854 if (action == AMOTION_EVENT_ACTION_DOWN) {
3855 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3856 "Split motion event has mismatching downTime and eventTime for "
3857 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3858 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3859 }
3860
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003861 int32_t newId = mIdGenerator.nextId();
3862 if (ATRACE_ENABLED()) {
3863 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3864 ") to MotionEvent(id=0x%" PRIx32 ").",
3865 originalMotionEntry.id, newId);
3866 ATRACE_NAME(message.c_str());
3867 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003868 std::unique_ptr<MotionEntry> splitMotionEntry =
3869 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3870 originalMotionEntry.deviceId, originalMotionEntry.source,
3871 originalMotionEntry.displayId,
3872 originalMotionEntry.policyFlags, action,
3873 originalMotionEntry.actionButton,
3874 originalMotionEntry.flags, originalMotionEntry.metaState,
3875 originalMotionEntry.buttonState,
3876 originalMotionEntry.classification,
3877 originalMotionEntry.edgeFlags,
3878 originalMotionEntry.xPrecision,
3879 originalMotionEntry.yPrecision,
3880 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003881 originalMotionEntry.yCursorPosition, splitDownTime,
3882 splitPointerCount, splitPointerProperties,
3883 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003885 if (originalMotionEntry.injectionState) {
3886 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 splitMotionEntry->injectionState->refCount += 1;
3888 }
3889
3890 return splitMotionEntry;
3891}
3892
3893void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003894 if (DEBUG_INBOUND_EVENT_DETAILS) {
3895 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897
Antonio Kantekf16f2832021-09-28 04:39:20 +00003898 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003902 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3903 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3904 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 } // release lock
3906
3907 if (needWake) {
3908 mLooper->wake();
3909 }
3910}
3911
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003912/**
3913 * If one of the meta shortcuts is detected, process them here:
3914 * Meta + Backspace -> generate BACK
3915 * Meta + Enter -> generate HOME
3916 * This will potentially overwrite keyCode and metaState.
3917 */
3918void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003919 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3921 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3922 if (keyCode == AKEYCODE_DEL) {
3923 newKeyCode = AKEYCODE_BACK;
3924 } else if (keyCode == AKEYCODE_ENTER) {
3925 newKeyCode = AKEYCODE_HOME;
3926 }
3927 if (newKeyCode != AKEYCODE_UNKNOWN) {
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 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003931 keyCode = newKeyCode;
3932 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3933 }
3934 } else if (action == AKEY_EVENT_ACTION_UP) {
3935 // In order to maintain a consistent stream of up and down events, check to see if the key
3936 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3937 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003938 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003939 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003940 auto replacementIt = mReplacedKeys.find(replacement);
3941 if (replacementIt != mReplacedKeys.end()) {
3942 keyCode = replacementIt->second;
3943 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003944 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3945 }
3946 }
3947}
3948
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003950 if (DEBUG_INBOUND_EVENT_DETAILS) {
3951 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3952 "policyFlags=0x%x, action=0x%x, "
3953 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3954 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3955 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3956 args->downTime);
3957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 if (!validateKeyEvent(args->action)) {
3959 return;
3960 }
3961
3962 uint32_t policyFlags = args->policyFlags;
3963 int32_t flags = args->flags;
3964 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003965 // InputDispatcher tracks and generates key repeats on behalf of
3966 // whatever notifies it, so repeatCount should always be set to 0
3967 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3969 policyFlags |= POLICY_FLAG_VIRTUAL;
3970 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 if (policyFlags & POLICY_FLAG_FUNCTION) {
3973 metaState |= AMETA_FUNCTION_ON;
3974 }
3975
3976 policyFlags |= POLICY_FLAG_TRUSTED;
3977
Michael Wright78f24442014-08-06 15:55:28 -07003978 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003979 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003980
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003982 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003983 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3984 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
Michael Wright2b3c3302018-03-02 17:19:13 +00003986 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003988 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3989 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003990 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
Antonio Kantekf16f2832021-09-28 04:39:20 +00003993 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 { // acquire lock
3995 mLock.lock();
3996
3997 if (shouldSendKeyToInputFilterLocked(args)) {
3998 mLock.unlock();
3999
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004000 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4002 return; // event was consumed by the filter
4003 }
4004
4005 mLock.lock();
4006 }
4007
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004008 std::unique_ptr<KeyEntry> newEntry =
4009 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4010 args->displayId, policyFlags, args->action, flags,
4011 keyCode, args->scanCode, metaState, repeatCount,
4012 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004014 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 mLock.unlock();
4016 } // release lock
4017
4018 if (needWake) {
4019 mLooper->wake();
4020 }
4021}
4022
4023bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4024 return mInputFilterEnabled;
4025}
4026
4027void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004028 if (DEBUG_INBOUND_EVENT_DETAILS) {
4029 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4030 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004031 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004032 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4033 "yCursorPosition=%f, downTime=%" PRId64,
4034 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004035 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4036 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4037 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4038 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004039 for (uint32_t i = 0; i < args->pointerCount; i++) {
4040 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4041 "x=%f, y=%f, pressure=%f, size=%f, "
4042 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4043 "orientation=%f",
4044 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4045 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4046 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4047 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4048 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4049 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4050 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4051 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4052 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4053 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4057 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 return;
4059 }
4060
4061 uint32_t policyFlags = args->policyFlags;
4062 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004063
4064 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004065 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004066 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4067 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004068 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Antonio Kantekf16f2832021-09-28 04:39:20 +00004071 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 { // acquire lock
4073 mLock.lock();
4074
4075 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004076 ui::Transform displayTransform;
4077 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4078 displayTransform = it->second.transform;
4079 }
4080
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 mLock.unlock();
4082
4083 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004084 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4085 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004086 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004087 displayTransform, args->xPrecision, args->yPrecision,
4088 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004089 args->downTime, args->eventTime, args->pointerCount,
4090 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
4092 policyFlags |= POLICY_FLAG_FILTERED;
4093 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4094 return; // event was consumed by the filter
4095 }
4096
4097 mLock.lock();
4098 }
4099
4100 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004101 std::unique_ptr<MotionEntry> newEntry =
4102 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4103 args->source, args->displayId, policyFlags,
4104 args->action, args->actionButton, args->flags,
4105 args->metaState, args->buttonState,
4106 args->classification, args->edgeFlags,
4107 args->xPrecision, args->yPrecision,
4108 args->xCursorPosition, args->yCursorPosition,
4109 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004110 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004112 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4113 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4114 !mInputFilterEnabled) {
4115 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4116 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4117 }
4118
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004119 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 mLock.unlock();
4121 } // release lock
4122
4123 if (needWake) {
4124 mLooper->wake();
4125 }
4126}
4127
Chris Yef59a2f42020-10-16 12:55:26 -07004128void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004129 if (DEBUG_INBOUND_EVENT_DETAILS) {
4130 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4131 " sensorType=%s",
4132 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004133 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004134 }
Chris Yef59a2f42020-10-16 12:55:26 -07004135
Antonio Kantekf16f2832021-09-28 04:39:20 +00004136 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004137 { // acquire lock
4138 mLock.lock();
4139
4140 // Just enqueue a new sensor event.
4141 std::unique_ptr<SensorEntry> newEntry =
4142 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4143 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4144 args->sensorType, args->accuracy,
4145 args->accuracyChanged, args->values);
4146
4147 needWake = enqueueInboundEventLocked(std::move(newEntry));
4148 mLock.unlock();
4149 } // release lock
4150
4151 if (needWake) {
4152 mLooper->wake();
4153 }
4154}
4155
Chris Yefb552902021-02-03 17:18:37 -08004156void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004157 if (DEBUG_INBOUND_EVENT_DETAILS) {
4158 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4159 args->deviceId, args->isOn);
4160 }
Chris Yefb552902021-02-03 17:18:37 -08004161 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4162}
4163
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004165 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166}
4167
4168void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004169 if (DEBUG_INBOUND_EVENT_DETAILS) {
4170 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4171 "switchMask=0x%08x",
4172 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
4175 uint32_t policyFlags = args->policyFlags;
4176 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004177 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178}
4179
4180void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004181 if (DEBUG_INBOUND_EVENT_DETAILS) {
4182 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4183 args->deviceId);
4184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185
Antonio Kantekf16f2832021-09-28 04:39:20 +00004186 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004188 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004190 std::unique_ptr<DeviceResetEntry> newEntry =
4191 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4192 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 } // release lock
4194
4195 if (needWake) {
4196 mLooper->wake();
4197 }
4198}
4199
Prabir Pradhan7e186182020-11-10 13:56:45 -08004200void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004201 if (DEBUG_INBOUND_EVENT_DETAILS) {
4202 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004203 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004204 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004205
Antonio Kantekf16f2832021-09-28 04:39:20 +00004206 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004207 { // acquire lock
4208 std::scoped_lock _l(mLock);
4209 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004210 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004211 needWake = enqueueInboundEventLocked(std::move(entry));
4212 } // release lock
4213
4214 if (needWake) {
4215 mLooper->wake();
4216 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004217}
4218
Prabir Pradhan5735a322022-04-11 17:23:34 +00004219InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4220 std::optional<int32_t> targetUid,
4221 InputEventInjectionSync syncMode,
4222 std::chrono::milliseconds timeout,
4223 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004224 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004225 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4226 "policyFlags=0x%08x",
4227 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4228 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004229 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004230 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
Prabir Pradhan5735a322022-04-11 17:23:34 +00004232 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004235 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4236 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4237 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4238 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4239 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004240 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004241 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004242 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 }
4244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004245 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004248 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4249 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004251 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004254 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004255 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4256 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4257 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004258 int32_t keyCode = incomingKey.getKeyCode();
4259 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004260 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004262 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004263 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004264 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4265 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4266 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4269 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004270 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271
4272 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4273 android::base::Timer t;
4274 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4275 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4276 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4277 std::to_string(t.duration().count()).c_str());
4278 }
4279 }
4280
4281 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 std::unique_ptr<KeyEntry> injectedEntry =
4283 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004285 incomingKey.getDisplayId(), policyFlags, action,
4286 flags, keyCode, incomingKey.getScanCode(), metaState,
4287 incomingKey.getRepeatCount(),
4288 incomingKey.getDownTime());
4289 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 }
4292
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004294 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004295 const int32_t action = motionEvent.getAction();
4296 const bool isPointerEvent =
4297 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4298 // If a pointer event has no displayId specified, inject it to the default display.
4299 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4300 ? ADISPLAY_ID_DEFAULT
4301 : event->getDisplayId();
4302 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004303 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004304 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004305 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 }
4309
4310 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004311 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 android::base::Timer t;
4313 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4314 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4315 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4316 std::to_string(t.duration().count()).c_str());
4317 }
4318 }
4319
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004320 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4321 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4322 }
4323
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004325 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4326 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004327 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004328 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4329 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004330 displayId, policyFlags, action, actionButton,
4331 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004332 motionEvent.getButtonState(),
4333 motionEvent.getClassification(),
4334 motionEvent.getEdgeFlags(),
4335 motionEvent.getXPrecision(),
4336 motionEvent.getYPrecision(),
4337 motionEvent.getRawXCursorPosition(),
4338 motionEvent.getRawYCursorPosition(),
4339 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004340 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004341 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004342 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004343 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004344 sampleEventTimes += 1;
4345 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004346 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004347 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4348 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004349 displayId, policyFlags, action, actionButton,
4350 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004351 motionEvent.getButtonState(),
4352 motionEvent.getClassification(),
4353 motionEvent.getEdgeFlags(),
4354 motionEvent.getXPrecision(),
4355 motionEvent.getYPrecision(),
4356 motionEvent.getRawXCursorPosition(),
4357 motionEvent.getRawYCursorPosition(),
4358 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004359 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004360 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004361 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4362 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004363 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 }
4365 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004368 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004369 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004370 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372
Prabir Pradhan5735a322022-04-11 17:23:34 +00004373 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004374 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 injectionState->injectionIsAsync = true;
4376 }
4377
4378 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004379 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
4381 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004382 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004383 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004384 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 }
4386
4387 mLock.unlock();
4388
4389 if (needWake) {
4390 mLooper->wake();
4391 }
4392
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004395 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004397 if (syncMode == InputEventInjectionSync::NONE) {
4398 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 } else {
4400 for (;;) {
4401 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 break;
4404 }
4405
4406 nsecs_t remainingTimeout = endTime - now();
4407 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004408 if (DEBUG_INJECTION) {
4409 ALOGD("injectInputEvent - Timed out waiting for injection result "
4410 "to become available.");
4411 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 break;
4414 }
4415
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004416 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
4418
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4420 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004422 if (DEBUG_INJECTION) {
4423 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4424 injectionState->pendingForegroundDispatches);
4425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 nsecs_t remainingTimeout = endTime - now();
4427 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004428 if (DEBUG_INJECTION) {
4429 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4430 "dispatches to finish.");
4431 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004432 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 break;
4434 }
4435
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004436 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 }
4438 }
4439 }
4440
4441 injectionState->release();
4442 } // release lock
4443
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004444 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004445 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447
4448 return injectionResult;
4449}
4450
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004451std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004452 std::array<uint8_t, 32> calculatedHmac;
4453 std::unique_ptr<VerifiedInputEvent> result;
4454 switch (event.getType()) {
4455 case AINPUT_EVENT_TYPE_KEY: {
4456 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4457 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4458 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004459 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004460 break;
4461 }
4462 case AINPUT_EVENT_TYPE_MOTION: {
4463 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4464 VerifiedMotionEvent verifiedMotionEvent =
4465 verifiedMotionEventFromMotionEvent(motionEvent);
4466 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004467 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004468 break;
4469 }
4470 default: {
4471 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4472 return nullptr;
4473 }
4474 }
4475 if (calculatedHmac == INVALID_HMAC) {
4476 return nullptr;
4477 }
4478 if (calculatedHmac != event.getHmac()) {
4479 return nullptr;
4480 }
4481 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004482}
4483
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004484void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004488 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004489 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004492 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 // Log the outcome since the injector did not wait for the injection result.
4494 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 ALOGV("Asynchronous input event injection succeeded.");
4497 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004498 case InputEventInjectionResult::TARGET_MISMATCH:
4499 ALOGV("Asynchronous input event injection target mismatch.");
4500 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004502 ALOGW("Asynchronous input event injection failed.");
4503 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004504 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004505 ALOGW("Asynchronous input event injection timed out.");
4506 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 case InputEventInjectionResult::PENDING:
4508 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4509 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 }
4511 }
4512
4513 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004514 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516}
4517
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004518void InputDispatcher::transformMotionEntryForInjectionLocked(
4519 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004520 // Input injection works in the logical display coordinate space, but the input pipeline works
4521 // display space, so we need to transform the injected events accordingly.
4522 const auto it = mDisplayInfos.find(entry.displayId);
4523 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004524 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004525
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004526 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4527 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4528 const vec2 cursor =
4529 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4530 {entry.xCursorPosition, entry.yCursorPosition});
4531 entry.xCursorPosition = cursor.x;
4532 entry.yCursorPosition = cursor.y;
4533 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004534 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004535 entry.pointerCoords[i] =
4536 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4537 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004538 }
4539}
4540
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004541void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4542 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 if (injectionState) {
4544 injectionState->pendingForegroundDispatches += 1;
4545 }
4546}
4547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004548void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4549 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 if (injectionState) {
4551 injectionState->pendingForegroundDispatches -= 1;
4552
4553 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004554 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 }
4556 }
4557}
4558
chaviw98318de2021-05-19 16:45:23 -05004559const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004560 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004561 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004562 auto it = mWindowHandlesByDisplay.find(displayId);
4563 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004564}
4565
chaviw98318de2021-05-19 16:45:23 -05004566sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004567 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004568 if (windowHandleToken == nullptr) {
4569 return nullptr;
4570 }
4571
Arthur Hungb92218b2018-08-14 12:00:21 +08004572 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004573 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4574 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004575 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004576 return windowHandle;
4577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 }
4579 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004580 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581}
4582
chaviw98318de2021-05-19 16:45:23 -05004583sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4584 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004585 if (windowHandleToken == nullptr) {
4586 return nullptr;
4587 }
4588
chaviw98318de2021-05-19 16:45:23 -05004589 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004590 if (windowHandle->getToken() == windowHandleToken) {
4591 return windowHandle;
4592 }
4593 }
4594 return nullptr;
4595}
4596
chaviw98318de2021-05-19 16:45:23 -05004597sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4598 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004599 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004600 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4601 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004602 if (handle->getId() == windowHandle->getId() &&
4603 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004604 if (windowHandle->getInfo()->displayId != it.first) {
4605 ALOGE("Found window %s in display %" PRId32
4606 ", but it should belong to display %" PRId32,
4607 windowHandle->getName().c_str(), it.first,
4608 windowHandle->getInfo()->displayId);
4609 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004610 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612 }
4613 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004614 return nullptr;
4615}
4616
chaviw98318de2021-05-19 16:45:23 -05004617sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004618 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4619 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620}
4621
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004622bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4623 const MotionEntry& motionEntry) const {
4624 const WindowInfo& info = *window->getInfo();
4625
4626 // Skip spy window targets that are not valid for targeted injection.
4627 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004628 return false;
4629 }
4630
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004631 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4632 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4633 return false;
4634 }
4635
4636 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4637 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4638 window->getName().c_str());
4639 return false;
4640 }
4641
4642 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004643 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004644 ALOGW("Not sending touch to %s because there's no corresponding connection",
4645 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004646 return false;
4647 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004648
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004649 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004650 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004651 return false;
4652 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004653
4654 // Drop events that can't be trusted due to occlusion
4655 const auto [x, y] = resolveTouchedPosition(motionEntry);
4656 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4657 if (!isTouchTrustedLocked(occlusionInfo)) {
4658 if (DEBUG_TOUCH_OCCLUSION) {
4659 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4660 for (const auto& log : occlusionInfo.debugInfo) {
4661 ALOGD("%s", log.c_str());
4662 }
4663 }
4664 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4665 occlusionInfo.obscuringUid);
4666 return false;
4667 }
4668
4669 // Drop touch events if requested by input feature
4670 if (shouldDropInput(motionEntry, window)) {
4671 return false;
4672 }
4673
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004674 return true;
4675}
4676
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004677std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4678 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004679 auto connectionIt = mConnectionsByToken.find(token);
4680 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004681 return nullptr;
4682 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004683 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004684}
4685
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004686void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004687 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4688 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004689 // Remove all handles on a display if there are no windows left.
4690 mWindowHandlesByDisplay.erase(displayId);
4691 return;
4692 }
4693
4694 // Since we compare the pointer of input window handles across window updates, we need
4695 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004696 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4697 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4698 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004699 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004700 }
4701
chaviw98318de2021-05-19 16:45:23 -05004702 std::vector<sp<WindowInfoHandle>> newHandles;
4703 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004704 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004705 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004706 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004707 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004708 const bool canReceiveInput =
4709 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4710 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004711 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004712 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004713 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004714 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004715 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004716 }
4717
4718 if (info->displayId != displayId) {
4719 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4720 handle->getName().c_str(), displayId, info->displayId);
4721 continue;
4722 }
4723
Robert Carredd13602020-04-13 17:24:34 -07004724 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4725 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004726 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004727 oldHandle->updateFrom(handle);
4728 newHandles.push_back(oldHandle);
4729 } else {
4730 newHandles.push_back(handle);
4731 }
4732 }
4733
4734 // Insert or replace
4735 mWindowHandlesByDisplay[displayId] = newHandles;
4736}
4737
Arthur Hung72d8dc32020-03-28 00:48:39 +00004738void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004739 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004740 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004741 { // acquire lock
4742 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004743 for (const auto& [displayId, handles] : handlesPerDisplay) {
4744 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004745 }
4746 }
4747 // Wake up poll loop since it may need to make new input dispatching choices.
4748 mLooper->wake();
4749}
4750
Arthur Hungb92218b2018-08-14 12:00:21 +08004751/**
4752 * Called from InputManagerService, update window handle list by displayId that can receive input.
4753 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4754 * If set an empty list, remove all handles from the specific display.
4755 * For focused handle, check if need to change and send a cancel event to previous one.
4756 * For removed handle, check if need to send a cancel event if already in touch.
4757 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004758void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004759 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004760 if (DEBUG_FOCUS) {
4761 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004762 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004763 windowList += iwh->getName() + " ";
4764 }
4765 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
Prabir Pradhand65552b2021-10-07 11:23:50 -07004768 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004769 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004770 const WindowInfo& info = *window->getInfo();
4771
4772 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004773 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004774 if (noInputWindow && window->getToken() != nullptr) {
4775 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4776 window->getName().c_str());
4777 window->releaseChannel();
4778 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004779
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004780 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004781 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4782 !info.inputConfig.test(
4783 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004784 "%s has feature SPY, but is not a trusted overlay.",
4785 window->getName().c_str());
4786
Prabir Pradhand65552b2021-10-07 11:23:50 -07004787 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004788 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4789 !info.inputConfig.test(
4790 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004791 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4792 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004793 }
4794
Arthur Hung72d8dc32020-03-28 00:48:39 +00004795 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004796 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004798 // Save the old windows' orientation by ID before it gets updated.
4799 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004800 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004801 oldWindowOrientations.emplace(handle->getId(),
4802 handle->getInfo()->transform.getOrientation());
4803 }
4804
chaviw98318de2021-05-19 16:45:23 -05004805 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004806
chaviw98318de2021-05-19 16:45:23 -05004807 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004808 if (mLastHoverWindowHandle &&
4809 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4810 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004811 mLastHoverWindowHandle = nullptr;
4812 }
4813
Vishnu Nairc519ff72021-01-21 08:23:08 -08004814 std::optional<FocusResolver::FocusChanges> changes =
4815 mFocusResolver.setInputWindows(displayId, windowHandles);
4816 if (changes) {
4817 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004820 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4821 mTouchStatesByDisplay.find(displayId);
4822 if (stateIt != mTouchStatesByDisplay.end()) {
4823 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004824 for (size_t i = 0; i < state.windows.size();) {
4825 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004826 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004827 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004828 ALOGD("Touched window was removed: %s in display %" PRId32,
4829 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004830 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004831 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004832 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4833 if (touchedInputChannel != nullptr) {
4834 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4835 "touched window was removed");
4836 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004837 // Since we are about to drop the touch, cancel the events for the wallpaper as
4838 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004839 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004840 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4841 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004842 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4843 if (wallpaper != nullptr) {
4844 sp<Connection> wallpaperConnection =
4845 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004846 if (wallpaperConnection != nullptr) {
4847 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4848 options);
4849 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004850 }
4851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004853 state.windows.erase(state.windows.begin() + i);
4854 } else {
4855 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 }
4857 }
arthurhungb89ccb02020-12-30 16:19:01 +08004858
arthurhung6d4bed92021-03-17 11:59:33 +08004859 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004860 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004861 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004862 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004863 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004864 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4865 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004866 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004867 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004868 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004869
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004870 // Determine if the orientation of any of the input windows have changed, and cancel all
4871 // pointer events if necessary.
4872 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4873 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4874 if (newWindowHandle != nullptr &&
4875 newWindowHandle->getInfo()->transform.getOrientation() !=
4876 oldWindowOrientations[oldWindowHandle->getId()]) {
4877 std::shared_ptr<InputChannel> inputChannel =
4878 getInputChannelLocked(newWindowHandle->getToken());
4879 if (inputChannel != nullptr) {
4880 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4881 "touched window's orientation changed");
4882 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004883 }
4884 }
4885 }
4886
Arthur Hung72d8dc32020-03-28 00:48:39 +00004887 // Release information for windows that are no longer present.
4888 // This ensures that unused input channels are released promptly.
4889 // Otherwise, they might stick around until the window handle is destroyed
4890 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004891 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004892 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004893 if (DEBUG_FOCUS) {
4894 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004895 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004896 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004897 }
chaviw291d88a2019-02-14 10:33:58 -08004898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899}
4900
4901void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004902 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004903 if (DEBUG_FOCUS) {
4904 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4905 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4906 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004907 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004908 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004909 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 } // release lock
4911
4912 // Wake up poll loop since it may need to make new input dispatching choices.
4913 mLooper->wake();
4914}
4915
Vishnu Nair599f1412021-06-21 10:39:58 -07004916void InputDispatcher::setFocusedApplicationLocked(
4917 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4918 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4919 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4920
4921 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4922 return; // This application is already focused. No need to wake up or change anything.
4923 }
4924
4925 // Set the new application handle.
4926 if (inputApplicationHandle != nullptr) {
4927 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4928 } else {
4929 mFocusedApplicationHandlesByDisplay.erase(displayId);
4930 }
4931
4932 // No matter what the old focused application was, stop waiting on it because it is
4933 // no longer focused.
4934 resetNoFocusedWindowTimeoutLocked();
4935}
4936
Tiger Huang721e26f2018-07-24 22:26:19 +08004937/**
4938 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4939 * the display not specified.
4940 *
4941 * We track any unreleased events for each window. If a window loses the ability to receive the
4942 * released event, we will send a cancel event to it. So when the focused display is changed, we
4943 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4944 * display. The display-specified events won't be affected.
4945 */
4946void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004947 if (DEBUG_FOCUS) {
4948 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4949 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004951 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004952
4953 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004954 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004955 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004956 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004957 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004958 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004959 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004960 CancelationOptions
4961 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4962 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004963 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004964 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4965 }
4966 }
4967 mFocusedDisplayId = displayId;
4968
Chris Ye3c2d6f52020-08-09 10:39:48 -07004969 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004970 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004971 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004972
Vishnu Nairad321cd2020-08-20 16:40:21 -07004973 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004974 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004975 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004976 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004977 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004978 }
4979 }
4980 }
4981
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004982 if (DEBUG_FOCUS) {
4983 logDispatchStateLocked();
4984 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004985 } // release lock
4986
4987 // Wake up poll loop since it may need to make new input dispatching choices.
4988 mLooper->wake();
4989}
4990
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004992 if (DEBUG_FOCUS) {
4993 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995
4996 bool changed;
4997 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004998 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999
5000 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5001 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 }
5004
5005 if (mDispatchEnabled && !enabled) {
5006 resetAndDropEverythingLocked("dispatcher is being disabled");
5007 }
5008
5009 mDispatchEnabled = enabled;
5010 mDispatchFrozen = frozen;
5011 changed = true;
5012 } else {
5013 changed = false;
5014 }
5015
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005016 if (DEBUG_FOCUS) {
5017 logDispatchStateLocked();
5018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 } // release lock
5020
5021 if (changed) {
5022 // Wake up poll loop since it may need to make new input dispatching choices.
5023 mLooper->wake();
5024 }
5025}
5026
5027void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005028 if (DEBUG_FOCUS) {
5029 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031
5032 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005033 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034
5035 if (mInputFilterEnabled == enabled) {
5036 return;
5037 }
5038
5039 mInputFilterEnabled = enabled;
5040 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5041 } // release lock
5042
5043 // Wake up poll loop since there might be work to do to drop everything.
5044 mLooper->wake();
5045}
5046
Antonio Kanteka042c022022-07-06 16:51:07 -07005047bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5048 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005049 bool needWake = false;
5050 {
5051 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005052 ALOGD_IF(DEBUG_TOUCH_MODE,
5053 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5054 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5055 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5056 mTouchModePerDisplay.count(displayId) == 0
5057 ? "not set"
5058 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5059
Antonio Kantek15beb512022-06-13 22:35:41 +00005060 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5061 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005062 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005063 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005064 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005065 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5066 !recentWindowsAreOwnedByLocked(pid, uid)) {
5067 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5068 "window nor none of the previously interacted window",
5069 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005070 return false;
5071 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005072 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005073 mTouchModePerDisplay[displayId] = inTouchMode;
5074 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5075 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005076 needWake = enqueueInboundEventLocked(std::move(entry));
5077 } // release lock
5078
5079 if (needWake) {
5080 mLooper->wake();
5081 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005082 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005083}
5084
Antonio Kantek48710e42022-03-24 14:19:30 -07005085bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5086 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5087 if (focusedToken == nullptr) {
5088 return false;
5089 }
5090 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5091 return isWindowOwnedBy(windowHandle, pid, uid);
5092}
5093
5094bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5095 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5096 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5097 const sp<WindowInfoHandle> windowHandle =
5098 getWindowHandleLocked(connectionToken);
5099 return isWindowOwnedBy(windowHandle, pid, uid);
5100 }) != mInteractionConnectionTokens.end();
5101}
5102
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005103void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5104 if (opacity < 0 || opacity > 1) {
5105 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5106 return;
5107 }
5108
5109 std::scoped_lock lock(mLock);
5110 mMaximumObscuringOpacityForTouch = opacity;
5111}
5112
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005113std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5114InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005115 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5116 for (TouchedWindow& w : state.windows) {
5117 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005118 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005119 }
5120 }
5121 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005122 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005123}
5124
arthurhungb89ccb02020-12-30 16:19:01 +08005125bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5126 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005127 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005128 if (DEBUG_FOCUS) {
5129 ALOGD("Trivial transfer to same window.");
5130 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005131 return true;
5132 }
5133
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005135 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136
Arthur Hungabbb9d82021-09-01 14:52:30 +00005137 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005138 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005139 if (state == nullptr || touchedWindow == nullptr) {
5140 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 return false;
5142 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005143
Arthur Hungabbb9d82021-09-01 14:52:30 +00005144 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5145 if (toWindowHandle == nullptr) {
5146 ALOGW("Cannot transfer focus because to window not found.");
5147 return false;
5148 }
5149
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005150 if (DEBUG_FOCUS) {
5151 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005152 touchedWindow->windowHandle->getName().c_str(),
5153 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155
Arthur Hungabbb9d82021-09-01 14:52:30 +00005156 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005157 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005158 BitSet32 pointerIds = touchedWindow->pointerIds;
5159 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160
Arthur Hungabbb9d82021-09-01 14:52:30 +00005161 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005162 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005163 ftl::Flags<InputTarget::Flags> newTargetFlags =
5164 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005165 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005166 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005167 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005168 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169
Arthur Hungabbb9d82021-09-01 14:52:30 +00005170 // Store the dragging window.
5171 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005172 if (pointerIds.count() != 1) {
5173 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5174 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005175 return false;
5176 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005177 // Track the pointer id for drag window and generate the drag state.
5178 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005179 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 }
5181
Arthur Hungabbb9d82021-09-01 14:52:30 +00005182 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005183 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5184 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005185 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005186 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005187 CancelationOptions
5188 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5189 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005191 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 }
5193
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005194 if (DEBUG_FOCUS) {
5195 logDispatchStateLocked();
5196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 } // release lock
5198
5199 // Wake up poll loop since it may need to make new input dispatching choices.
5200 mLooper->wake();
5201 return true;
5202}
5203
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005204/**
5205 * Get the touched foreground window on the given display.
5206 * Return null if there are no windows touched on that display, or if more than one foreground
5207 * window is being touched.
5208 */
5209sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5210 auto stateIt = mTouchStatesByDisplay.find(displayId);
5211 if (stateIt == mTouchStatesByDisplay.end()) {
5212 ALOGI("No touch state on display %" PRId32, displayId);
5213 return nullptr;
5214 }
5215
5216 const TouchState& state = stateIt->second;
5217 sp<WindowInfoHandle> touchedForegroundWindow;
5218 // If multiple foreground windows are touched, return nullptr
5219 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005220 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005221 if (touchedForegroundWindow != nullptr) {
5222 ALOGI("Two or more foreground windows: %s and %s",
5223 touchedForegroundWindow->getName().c_str(),
5224 window.windowHandle->getName().c_str());
5225 return nullptr;
5226 }
5227 touchedForegroundWindow = window.windowHandle;
5228 }
5229 }
5230 return touchedForegroundWindow;
5231}
5232
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005233// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005234bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005235 sp<IBinder> fromToken;
5236 { // acquire lock
5237 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005238 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005239 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005240 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5241 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005242 return false;
5243 }
5244
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005245 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5246 if (from == nullptr) {
5247 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5248 return false;
5249 }
5250
5251 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005252 } // release lock
5253
5254 return transferTouchFocus(fromToken, destChannelToken);
5255}
5256
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005258 if (DEBUG_FOCUS) {
5259 ALOGD("Resetting and dropping all events (%s).", reason);
5260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261
5262 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5263 synthesizeCancelationEventsForAllConnectionsLocked(options);
5264
5265 resetKeyRepeatLocked();
5266 releasePendingEventLocked();
5267 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005268 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005270 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005271 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005273 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274}
5275
5276void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005277 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 dumpDispatchStateLocked(dump);
5279
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005280 std::istringstream stream(dump);
5281 std::string line;
5282
5283 while (std::getline(stream, line, '\n')) {
5284 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
5286}
5287
Prabir Pradhan99987712020-11-10 18:43:05 -08005288std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5289 std::string dump;
5290
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005291 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5292 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005293
5294 std::string windowName = "None";
5295 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005296 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005297 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5298 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5299 : "token has capture without window";
5300 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005301 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005302
5303 return dump;
5304}
5305
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005307 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5308 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5309 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005310 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311
Tiger Huang721e26f2018-07-24 22:26:19 +08005312 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5313 dump += StringPrintf(INDENT "FocusedApplications:\n");
5314 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5315 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005316 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005317 const std::chrono::duration timeout =
5318 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005319 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005320 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005321 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005324 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005326
Vishnu Nairc519ff72021-01-21 08:23:08 -08005327 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005328 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005330 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005331 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005332 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005333 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5334 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005337 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 }
5339
arthurhung6d4bed92021-03-17 11:59:33 +08005340 if (mDragState) {
5341 dump += StringPrintf(INDENT "DragState:\n");
5342 mDragState->dump(dump, INDENT2);
5343 }
5344
Arthur Hungb92218b2018-08-14 12:00:21 +08005345 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005346 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5347 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5348 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5349 const auto& displayInfo = it->second;
5350 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5351 displayInfo.logicalHeight);
5352 displayInfo.transform.dump(dump, "transform", INDENT4);
5353 } else {
5354 dump += INDENT2 "No DisplayInfo found!\n";
5355 }
5356
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005357 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005358 dump += INDENT2 "Windows:\n";
5359 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005360 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5361 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005363 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005364 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005365 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005366 "applicationInfo.name=%s, "
5367 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005368 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005369 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005370 windowInfo->displayId,
5371 windowInfo->inputConfig.string().c_str(),
5372 windowInfo->alpha, windowInfo->frameLeft,
5373 windowInfo->frameTop, windowInfo->frameRight,
5374 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005375 windowInfo->applicationInfo.name.c_str(),
5376 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005377 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005378 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005379 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005380 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005381 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005382 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005383 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005384 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005385 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005386 }
5387 } else {
5388 dump += INDENT2 "Windows: <none>\n";
5389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 }
5391 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005392 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 }
5394
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005395 if (!mGlobalMonitorsByDisplay.empty()) {
5396 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5397 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005398 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005401 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005404 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405
5406 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005407 if (!mRecentQueue.empty()) {
5408 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005409 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005410 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005411 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005412 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 }
5414 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005415 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 }
5417
5418 // Dump event currently being dispatched.
5419 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005420 dump += INDENT "PendingEvent:\n";
5421 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005422 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005423 dump += StringPrintf(", age=%" PRId64 "ms\n",
5424 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005426 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 }
5428
5429 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005430 if (!mInboundQueue.empty()) {
5431 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005432 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005433 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005434 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005435 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 }
5437 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005438 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 }
5440
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005441 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005442 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005443 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5444 const KeyReplacement& replacement = pair.first;
5445 int32_t newKeyCode = pair.second;
5446 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005447 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005448 }
5449 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005450 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005451 }
5452
Prabir Pradhancef936d2021-07-21 16:17:52 +00005453 if (!mCommandQueue.empty()) {
5454 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5455 } else {
5456 dump += INDENT "CommandQueue: <empty>\n";
5457 }
5458
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005459 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005460 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005461 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005462 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005463 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005464 connection->inputChannel->getFd().get(),
5465 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005466 connection->getWindowName().c_str(),
5467 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005468 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005470 if (!connection->outboundQueue.empty()) {
5471 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5472 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005473 dump += dumpQueue(connection->outboundQueue, currentTime);
5474
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005476 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 }
5478
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005479 if (!connection->waitQueue.empty()) {
5480 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5481 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005482 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005484 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 }
5486 }
5487 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005488 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489 }
5490
5491 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005492 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5493 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005495 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 }
5497
Antonio Kantek15beb512022-06-13 22:35:41 +00005498 if (!mTouchModePerDisplay.empty()) {
5499 dump += INDENT "TouchModePerDisplay:\n";
5500 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5501 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5502 std::to_string(touchMode).c_str());
5503 }
5504 } else {
5505 dump += INDENT "TouchModePerDisplay: <none>\n";
5506 }
5507
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005508 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005509 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5510 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5511 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005512 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005513 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514}
5515
Michael Wright3dd60e22019-03-27 22:06:44 +00005516void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5517 const size_t numMonitors = monitors.size();
5518 for (size_t i = 0; i < numMonitors; i++) {
5519 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005520 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005521 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5522 dump += "\n";
5523 }
5524}
5525
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005526class LooperEventCallback : public LooperCallback {
5527public:
5528 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5529 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5530
5531private:
5532 std::function<int(int events)> mCallback;
5533};
5534
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005535Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005536 if (DEBUG_CHANNEL_CREATION) {
5537 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005540 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005541 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005542 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005543
5544 if (result) {
5545 return base::Error(result) << "Failed to open input channel pair with name " << name;
5546 }
5547
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005549 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005550 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005551 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005552 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005553 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005555 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5556 ALOGE("Created a new connection, but the token %p is already known", token.get());
5557 }
5558 mConnectionsByToken.emplace(token, connection);
5559
5560 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5561 this, std::placeholders::_1, token);
5562
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005563 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5564 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565 } // release lock
5566
5567 // Wake the looper because some connections have changed.
5568 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005569 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570}
5571
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005572Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005573 const std::string& name,
5574 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005575 std::shared_ptr<InputChannel> serverChannel;
5576 std::unique_ptr<InputChannel> clientChannel;
5577 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5578 if (result) {
5579 return base::Error(result) << "Failed to open input channel pair with name " << name;
5580 }
5581
Michael Wright3dd60e22019-03-27 22:06:44 +00005582 { // acquire lock
5583 std::scoped_lock _l(mLock);
5584
5585 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005586 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5587 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005588 }
5589
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005590 sp<Connection> connection =
5591 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005592 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005593 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005594
5595 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5596 ALOGE("Created a new connection, but the token %p is already known", token.get());
5597 }
5598 mConnectionsByToken.emplace(token, connection);
5599 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5600 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005601
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005602 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005603
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005604 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5605 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005606 }
Garfield Tan15601662020-09-22 15:32:38 -07005607
Michael Wright3dd60e22019-03-27 22:06:44 +00005608 // Wake the looper because some connections have changed.
5609 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005610 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005611}
5612
Garfield Tan15601662020-09-22 15:32:38 -07005613status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005615 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616
Garfield Tan15601662020-09-22 15:32:38 -07005617 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 if (status) {
5619 return status;
5620 }
5621 } // release lock
5622
5623 // Wake the poll loop because removing the connection may have changed the current
5624 // synchronization state.
5625 mLooper->wake();
5626 return OK;
5627}
5628
Garfield Tan15601662020-09-22 15:32:38 -07005629status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5630 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005631 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005632 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005633 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 return BAD_VALUE;
5635 }
5636
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005637 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005638
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005640 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 }
5642
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005643 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644
5645 nsecs_t currentTime = now();
5646 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5647
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005648 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 return OK;
5650}
5651
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005652void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005653 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5654 auto& [displayId, monitors] = *it;
5655 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5656 return monitor.inputChannel->getConnectionToken() == connectionToken;
5657 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005658
Michael Wright3dd60e22019-03-27 22:06:44 +00005659 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005660 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005661 } else {
5662 ++it;
5663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 }
5665}
5666
Michael Wright3dd60e22019-03-27 22:06:44 +00005667status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005668 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005669 return pilferPointersLocked(token);
5670}
Michael Wright3dd60e22019-03-27 22:06:44 +00005671
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005672status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005673 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5674 if (!requestingChannel) {
5675 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5676 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005677 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005678
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005679 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005680 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005681 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5682 " Ignoring.");
5683 return BAD_VALUE;
5684 }
5685
5686 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005687 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005688 // Send cancel events to all the input channels we're stealing from.
5689 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5690 "input channel stole pointer stream");
5691 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005692 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005693 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005694 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005695 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005696 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005697 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005698 if (channel != nullptr && channel->getConnectionToken() != token) {
5699 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5700 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5701 canceledWindows += channel->getName();
5702 }
5703 }
5704 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5705 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5706 canceledWindows.c_str());
5707
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005708 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005709 // This only blocks relevant pointers to be sent to other windows
5710 window.isPilferingPointers = true;
5711
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005712 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005713 return OK;
5714}
5715
Prabir Pradhan99987712020-11-10 18:43:05 -08005716void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5717 { // acquire lock
5718 std::scoped_lock _l(mLock);
5719 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005720 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005721 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5722 windowHandle != nullptr ? windowHandle->getName().c_str()
5723 : "token without window");
5724 }
5725
Vishnu Nairc519ff72021-01-21 08:23:08 -08005726 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005727 if (focusedToken != windowToken) {
5728 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5729 enabled ? "enable" : "disable");
5730 return;
5731 }
5732
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005733 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005734 ALOGW("Ignoring request to %s Pointer Capture: "
5735 "window has %s requested pointer capture.",
5736 enabled ? "enable" : "disable", enabled ? "already" : "not");
5737 return;
5738 }
5739
Christine Franksb768bb42021-11-29 12:11:31 -08005740 if (enabled) {
5741 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5742 mIneligibleDisplaysForPointerCapture.end(),
5743 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5744 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5745 return;
5746 }
5747 }
5748
Prabir Pradhan99987712020-11-10 18:43:05 -08005749 setPointerCaptureLocked(enabled);
5750 } // release lock
5751
5752 // Wake the thread to process command entries.
5753 mLooper->wake();
5754}
5755
Christine Franksb768bb42021-11-29 12:11:31 -08005756void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5757 { // acquire lock
5758 std::scoped_lock _l(mLock);
5759 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5760 if (!isEligible) {
5761 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5762 }
5763 } // release lock
5764}
5765
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005766std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5767 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005768 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005769 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005770 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005771 }
5772 }
5773 }
5774 return std::nullopt;
5775}
5776
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005777sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005778 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005779 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005780 }
5781
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005782 for (const auto& [token, connection] : mConnectionsByToken) {
5783 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005784 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
5786 }
Robert Carr4e670e52018-08-15 13:26:12 -07005787
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005788 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789}
5790
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005791std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5792 sp<Connection> connection = getConnectionLocked(connectionToken);
5793 if (connection == nullptr) {
5794 return "<nullptr>";
5795 }
5796 return connection->getInputChannelName();
5797}
5798
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005799void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005800 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005801 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005802}
5803
Prabir Pradhancef936d2021-07-21 16:17:52 +00005804void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5805 const sp<Connection>& connection, uint32_t seq,
5806 bool handled, nsecs_t consumeTime) {
5807 // Handle post-event policy actions.
5808 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5809 if (dispatchEntryIt == connection->waitQueue.end()) {
5810 return;
5811 }
5812 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5813 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5814 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5815 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5816 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5817 }
5818 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5819 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5820 connection->inputChannel->getConnectionToken(),
5821 dispatchEntry->deliveryTime, consumeTime, finishTime);
5822 }
5823
5824 bool restartEvent;
5825 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5826 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5827 restartEvent =
5828 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5829 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5830 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5831 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5832 handled);
5833 } else {
5834 restartEvent = false;
5835 }
5836
5837 // Dequeue the event and start the next cycle.
5838 // Because the lock might have been released, it is possible that the
5839 // contents of the wait queue to have been drained, so we need to double-check
5840 // a few things.
5841 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5842 if (dispatchEntryIt != connection->waitQueue.end()) {
5843 dispatchEntry = *dispatchEntryIt;
5844 connection->waitQueue.erase(dispatchEntryIt);
5845 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5846 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5847 if (!connection->responsive) {
5848 connection->responsive = isConnectionResponsive(*connection);
5849 if (connection->responsive) {
5850 // The connection was unresponsive, and now it's responsive.
5851 processConnectionResponsiveLocked(*connection);
5852 }
5853 }
5854 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005855 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005856 connection->outboundQueue.push_front(dispatchEntry);
5857 traceOutboundQueueLength(*connection);
5858 } else {
5859 releaseDispatchEntry(dispatchEntry);
5860 }
5861 }
5862
5863 // Start the next dispatch cycle for this connection.
5864 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865}
5866
Prabir Pradhancef936d2021-07-21 16:17:52 +00005867void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5868 const sp<IBinder>& newToken) {
5869 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5870 scoped_unlock unlock(mLock);
5871 mPolicy->notifyFocusChanged(oldToken, newToken);
5872 };
5873 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874}
5875
Prabir Pradhancef936d2021-07-21 16:17:52 +00005876void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5877 auto command = [this, token, x, y]() REQUIRES(mLock) {
5878 scoped_unlock unlock(mLock);
5879 mPolicy->notifyDropWindow(token, x, y);
5880 };
5881 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005882}
5883
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005884void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5885 if (connection == nullptr) {
5886 LOG_ALWAYS_FATAL("Caller must check for nullness");
5887 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005888 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5889 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005890 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005891 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005892 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005893 return;
5894 }
5895 /**
5896 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5897 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5898 * has changed. This could cause newer entries to time out before the already dispatched
5899 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5900 * processes the events linearly. So providing information about the oldest entry seems to be
5901 * most useful.
5902 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005903 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005904 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5905 std::string reason =
5906 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005907 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005908 ns2ms(currentWait),
5909 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005910 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005911 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005912
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005913 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5914
5915 // Stop waking up for events on this connection, it is already unresponsive
5916 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005917}
5918
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005919void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5920 std::string reason =
5921 StringPrintf("%s does not have a focused window", application->getName().c_str());
5922 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005923
Prabir Pradhancef936d2021-07-21 16:17:52 +00005924 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5925 scoped_unlock unlock(mLock);
5926 mPolicy->notifyNoFocusedWindowAnr(application);
5927 };
5928 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005929}
5930
chaviw98318de2021-05-19 16:45:23 -05005931void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005932 const std::string& reason) {
5933 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5934 updateLastAnrStateLocked(windowLabel, reason);
5935}
5936
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005937void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5938 const std::string& reason) {
5939 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005940 updateLastAnrStateLocked(windowLabel, reason);
5941}
5942
5943void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5944 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005946 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 struct tm tm;
5948 localtime_r(&t, &tm);
5949 char timestr[64];
5950 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005951 mLastAnrState.clear();
5952 mLastAnrState += INDENT "ANR:\n";
5953 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005954 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5955 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005956 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957}
5958
Prabir Pradhancef936d2021-07-21 16:17:52 +00005959void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5960 KeyEntry& entry) {
5961 const KeyEvent event = createKeyEvent(entry);
5962 nsecs_t delay = 0;
5963 { // release lock
5964 scoped_unlock unlock(mLock);
5965 android::base::Timer t;
5966 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5967 entry.policyFlags);
5968 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5969 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5970 std::to_string(t.duration().count()).c_str());
5971 }
5972 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973
5974 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005975 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005976 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005977 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005979 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5980 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982}
5983
Prabir Pradhancef936d2021-07-21 16:17:52 +00005984void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005985 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005986 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005987 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005988 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005989 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005990 };
5991 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005992}
5993
Prabir Pradhanedd96402022-02-15 01:46:16 -08005994void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5995 std::optional<int32_t> pid) {
5996 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005997 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005998 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005999 };
6000 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006001}
6002
6003/**
6004 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6005 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6006 * command entry to the command queue.
6007 */
6008void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6009 std::string reason) {
6010 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006011 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006012 if (connection.monitor) {
6013 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6014 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006015 pid = findMonitorPidByTokenLocked(connectionToken);
6016 } else {
6017 // The connection is a window
6018 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6019 reason.c_str());
6020 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6021 if (handle != nullptr) {
6022 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006023 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006024 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006025 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026}
6027
6028/**
6029 * Tell the policy that a connection has become responsive so that it can stop ANR.
6030 */
6031void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6032 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006033 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006035 pid = findMonitorPidByTokenLocked(connectionToken);
6036 } else {
6037 // The connection is a window
6038 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6039 if (handle != nullptr) {
6040 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006041 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006042 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006043 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006044}
6045
Prabir Pradhancef936d2021-07-21 16:17:52 +00006046bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006047 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006048 KeyEntry& keyEntry, bool handled) {
6049 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006050 if (!handled) {
6051 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006053 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 return false;
6055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006057 // Get the fallback key state.
6058 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006059 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006060 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006061 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006062 connection->inputState.removeFallbackKey(originalKeyCode);
6063 }
6064
6065 if (handled || !dispatchEntry->hasForegroundTarget()) {
6066 // If the application handles the original key for which we previously
6067 // generated a fallback or if the window is not a foreground window,
6068 // then cancel the associated fallback key, if any.
6069 if (fallbackKeyCode != -1) {
6070 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006071 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6072 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6073 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6074 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6075 keyEntry.policyFlags);
6076 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006077 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006078 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079
6080 mLock.unlock();
6081
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006082 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006083 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084
6085 mLock.lock();
6086
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006087 // Cancel the fallback key.
6088 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 "application handled the original non-fallback key "
6091 "or is no longer a foreground target, "
6092 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093 options.keyCode = fallbackKeyCode;
6094 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096 connection->inputState.removeFallbackKey(originalKeyCode);
6097 }
6098 } else {
6099 // If the application did not handle a non-fallback key, first check
6100 // that we are in a good state to perform unhandled key event processing
6101 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006102 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006103 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006104 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6105 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6106 "since this is not an initial down. "
6107 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6108 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6109 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006110 return false;
6111 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006113 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006114 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6115 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6116 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6117 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6118 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006119 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120
6121 mLock.unlock();
6122
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006123 bool fallback =
6124 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006125 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006126
6127 mLock.lock();
6128
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006129 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006130 connection->inputState.removeFallbackKey(originalKeyCode);
6131 return false;
6132 }
6133
6134 // Latch the fallback keycode for this key on an initial down.
6135 // The fallback keycode cannot change at any other point in the lifecycle.
6136 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006137 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006138 fallbackKeyCode = event.getKeyCode();
6139 } else {
6140 fallbackKeyCode = AKEYCODE_UNKNOWN;
6141 }
6142 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6143 }
6144
6145 ALOG_ASSERT(fallbackKeyCode != -1);
6146
6147 // Cancel the fallback key if the policy decides not to send it anymore.
6148 // We will continue to dispatch the key to the policy but we will no
6149 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006150 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6151 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006152 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6153 if (fallback) {
6154 ALOGD("Unhandled key event: Policy requested to send key %d"
6155 "as a fallback for %d, but on the DOWN it had requested "
6156 "to send %d instead. Fallback canceled.",
6157 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6158 } else {
6159 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6160 "but on the DOWN it had requested to send %d. "
6161 "Fallback canceled.",
6162 originalKeyCode, fallbackKeyCode);
6163 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006164 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006165
6166 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6167 "canceling fallback, policy no longer desires it");
6168 options.keyCode = fallbackKeyCode;
6169 synthesizeCancelationEventsForConnectionLocked(connection, options);
6170
6171 fallback = false;
6172 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006173 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006174 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006175 }
6176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006177
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006178 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6179 {
6180 std::string msg;
6181 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6182 connection->inputState.getFallbackKeys();
6183 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6184 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6185 }
6186 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6187 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006189 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190
6191 if (fallback) {
6192 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006193 keyEntry.eventTime = event.getEventTime();
6194 keyEntry.deviceId = event.getDeviceId();
6195 keyEntry.source = event.getSource();
6196 keyEntry.displayId = event.getDisplayId();
6197 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6198 keyEntry.keyCode = fallbackKeyCode;
6199 keyEntry.scanCode = event.getScanCode();
6200 keyEntry.metaState = event.getMetaState();
6201 keyEntry.repeatCount = event.getRepeatCount();
6202 keyEntry.downTime = event.getDownTime();
6203 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006204
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006205 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6206 ALOGD("Unhandled key event: Dispatching fallback key. "
6207 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6208 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6209 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006210 return true; // restart the event
6211 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006212 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6213 ALOGD("Unhandled key event: No fallback key.");
6214 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006215
6216 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006217 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 }
6219 }
6220 return false;
6221}
6222
Prabir Pradhancef936d2021-07-21 16:17:52 +00006223bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006224 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006225 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 return false;
6227}
6228
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229void InputDispatcher::traceInboundQueueLengthLocked() {
6230 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006231 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232 }
6233}
6234
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006235void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 if (ATRACE_ENABLED()) {
6237 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006238 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6239 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 }
6241}
6242
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006243void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244 if (ATRACE_ENABLED()) {
6245 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006246 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6247 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 }
6249}
6250
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006251void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006252 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006254 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255 dumpDispatchStateLocked(dump);
6256
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006257 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006258 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006259 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 }
6261}
6262
6263void InputDispatcher::monitor() {
6264 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006265 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006266 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006267 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268}
6269
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006270/**
6271 * Wake up the dispatcher and wait until it processes all events and commands.
6272 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6273 * this method can be safely called from any thread, as long as you've ensured that
6274 * the work you are interested in completing has already been queued.
6275 */
6276bool InputDispatcher::waitForIdle() {
6277 /**
6278 * Timeout should represent the longest possible time that a device might spend processing
6279 * events and commands.
6280 */
6281 constexpr std::chrono::duration TIMEOUT = 100ms;
6282 std::unique_lock lock(mLock);
6283 mLooper->wake();
6284 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6285 return result == std::cv_status::no_timeout;
6286}
6287
Vishnu Naire798b472020-07-23 13:52:21 -07006288/**
6289 * Sets focus to the window identified by the token. This must be called
6290 * after updating any input window handles.
6291 *
6292 * Params:
6293 * request.token - input channel token used to identify the window that should gain focus.
6294 * request.focusedToken - the token that the caller expects currently to be focused. If the
6295 * specified token does not match the currently focused window, this request will be dropped.
6296 * If the specified focused token matches the currently focused window, the call will succeed.
6297 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6298 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6299 * when requesting the focus change. This determines which request gets
6300 * precedence if there is a focus change request from another source such as pointer down.
6301 */
Vishnu Nair958da932020-08-21 17:12:37 -07006302void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6303 { // acquire lock
6304 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006305 std::optional<FocusResolver::FocusChanges> changes =
6306 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6307 if (changes) {
6308 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006309 }
6310 } // release lock
6311 // Wake up poll loop since it may need to make new input dispatching choices.
6312 mLooper->wake();
6313}
6314
Vishnu Nairc519ff72021-01-21 08:23:08 -08006315void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6316 if (changes.oldFocus) {
6317 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006318 if (focusedInputChannel) {
6319 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6320 "focus left window");
6321 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006322 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006323 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006324 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006325 if (changes.newFocus) {
6326 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006327 }
6328
Prabir Pradhan99987712020-11-10 18:43:05 -08006329 // If a window has pointer capture, then it must have focus. We need to ensure that this
6330 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6331 // If the window loses focus before it loses pointer capture, then the window can be in a state
6332 // where it has pointer capture but not focus, violating the contract. Therefore we must
6333 // dispatch the pointer capture event before the focus event. Since focus events are added to
6334 // the front of the queue (above), we add the pointer capture event to the front of the queue
6335 // after the focus events are added. This ensures the pointer capture event ends up at the
6336 // front.
6337 disablePointerCaptureForcedLocked();
6338
Vishnu Nairc519ff72021-01-21 08:23:08 -08006339 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006340 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006341 }
6342}
Vishnu Nair958da932020-08-21 17:12:37 -07006343
Prabir Pradhan99987712020-11-10 18:43:05 -08006344void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006345 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006346 return;
6347 }
6348
6349 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6350
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006351 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006352 setPointerCaptureLocked(false);
6353 }
6354
6355 if (!mWindowTokenWithPointerCapture) {
6356 // No need to send capture changes because no window has capture.
6357 return;
6358 }
6359
6360 if (mPendingEvent != nullptr) {
6361 // Move the pending event to the front of the queue. This will give the chance
6362 // for the pending event to be dropped if it is a captured event.
6363 mInboundQueue.push_front(mPendingEvent);
6364 mPendingEvent = nullptr;
6365 }
6366
6367 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006368 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006369 mInboundQueue.push_front(std::move(entry));
6370}
6371
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006372void InputDispatcher::setPointerCaptureLocked(bool enable) {
6373 mCurrentPointerCaptureRequest.enable = enable;
6374 mCurrentPointerCaptureRequest.seq++;
6375 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006376 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006377 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006378 };
6379 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006380}
6381
Vishnu Nair599f1412021-06-21 10:39:58 -07006382void InputDispatcher::displayRemoved(int32_t displayId) {
6383 { // acquire lock
6384 std::scoped_lock _l(mLock);
6385 // Set an empty list to remove all handles from the specific display.
6386 setInputWindowsLocked(/* window handles */ {}, displayId);
6387 setFocusedApplicationLocked(displayId, nullptr);
6388 // Call focus resolver to clean up stale requests. This must be called after input windows
6389 // have been removed for the removed display.
6390 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006391 // Reset pointer capture eligibility, regardless of previous state.
6392 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006393 // Remove the associated touch mode state.
6394 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006395 } // release lock
6396
6397 // Wake up poll loop since it may need to make new input dispatching choices.
6398 mLooper->wake();
6399}
6400
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006401void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6402 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006403 // The listener sends the windows as a flattened array. Separate the windows by display for
6404 // more convenient parsing.
6405 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006406 for (const auto& info : windowInfos) {
6407 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006408 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006409 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006410
6411 { // acquire lock
6412 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006413
6414 // Ensure that we have an entry created for all existing displays so that if a displayId has
6415 // no windows, we can tell that the windows were removed from the display.
6416 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6417 handlesPerDisplay[displayId];
6418 }
6419
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006420 mDisplayInfos.clear();
6421 for (const auto& displayInfo : displayInfos) {
6422 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6423 }
6424
6425 for (const auto& [displayId, handles] : handlesPerDisplay) {
6426 setInputWindowsLocked(handles, displayId);
6427 }
6428 }
6429 // Wake up poll loop since it may need to make new input dispatching choices.
6430 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006431}
6432
Vishnu Nair062a8672021-09-03 16:07:44 -07006433bool InputDispatcher::shouldDropInput(
6434 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006435 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6436 (windowHandle->getInfo()->inputConfig.test(
6437 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006438 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006439 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6440 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006441 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006442 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006443 windowHandle->getInfo()->displayId);
6444 return true;
6445 }
6446 return false;
6447}
6448
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006449void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6450 const std::vector<gui::WindowInfo>& windowInfos,
6451 const std::vector<DisplayInfo>& displayInfos) {
6452 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6453}
6454
Arthur Hungdfd528e2021-12-08 13:23:04 +00006455void InputDispatcher::cancelCurrentTouch() {
6456 {
6457 std::scoped_lock _l(mLock);
6458 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6459 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6460 "cancel current touch");
6461 synthesizeCancelationEventsForAllConnectionsLocked(options);
6462
6463 mTouchStatesByDisplay.clear();
6464 mLastHoverWindowHandle.clear();
6465 }
6466 // Wake up poll loop since there might be work to do.
6467 mLooper->wake();
6468}
6469
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006470void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6471 std::scoped_lock _l(mLock);
6472 mMonitorDispatchingTimeout = timeout;
6473}
6474
Garfield Tane84e6f92019-08-29 17:28:41 -07006475} // namespace android::inputdispatcher